How to To Create Dynamic Submenu's in WPF

For creating dynamic sub-menus, <MenuItem.ItemContainerStyle> must be used instead of using <MenuItem.ItemTemtplae>; Try to avoid using ItemTemplate , specially a MenuItem should not be used inside an ItemTemplate as it creates two menu items for a sub-menu.

Here is a very good article explaining the difference and usage of each - http://weblogs.asp.net/okloeten/archive/2007/11/14/5149692.aspx

<MenuItem.ItemContainerStyle>
    <Style
        TargetType="{x:Type MenuItem}">
        <EventSetter
            Event="Click"
            Handler="HandleMenuItemApplyPreset_Click" />
        <Setter
            Property="Header"
            Value="{Binding Path=Title}" />
    </Style>
</MenuItem.ItemContainerStyle>

But, In some special cases it is required to use these two in conjunction (e.g. for displaying complex header) -

<MenuItem.ItemContainerStyle>
    <Style
        TargetType="{x:Type MenuItem}">
        <Setter
            Property="IsCheckable"
            Value="True" />
        <EventSetter
            Event="Checked"
            Handler="HandleMenuItemSelectScenario_Checked" />
        <Setter
            Property="IsChecked">
            <Setter.Value>
                <Binding
                    RelativeSource="{RelativeSource FindAncestor, AncestorType=ContextMenu}"
                    Path="PlacementTarget.ScenarioCollectionView.SelectedScenario.IsChecked" />
                <Binding />
            </Setter.Value>
        </Setter>
    </Style>
</MenuItem.ItemContainerStyle>
<MenuItem.ItemTemplate>
    <DataTemplate>
        <StackPanel
            Orientation="Horizontal">
            <TextBlock
                Text="{Binding Path=Record.MasterComponent}"
                Opacity="0.5"
                Margin="0,0,4,0" />
            <TextBlock
                Text="{Binding Path=Record.GlobalDisplayNameWithBrackets}" />
        </StackPanel>
    </DataTemplate>
</MenuItem.ItemTemplate>

1 Comment

Add a Comment

As it will appear on the website

Not displayed

Your website