使用动态MenuItems样式WPF-ContextMenu

时间:2016-04-26 15:33:31

标签: c# wpf xaml contextmenu

我有一个样式的ContextMenu。

<ContextMenu x:Key="ComboBoxContextMenu" Style="{StaticResource style_ContextMenu}">
    <ContextMenu.ItemsSource>
        <CompositeCollection>
            <MenuItem Style="{StaticResource style_MenutItem}" Header="{Binding ExtraMenuItem1}" Visibility="{Binding ExtraMenuItem1Visibility, Converter={StaticResource BoolToVisibilityConverter}}" Command="{Binding ExtraMenuItemCommand}" CommandParameter="MenuItem1_Click" />
        </CompositeCollection>
    </ContextMenu.ItemsSource>
</ContextMenu>

一切都很好看。如果我用ViewModel-First方法替换MenuItems,那么在样式被破坏时一切正常。 我该如何解救设计?当我在代码中添加MenuItems时,是否会得到像ListBox这样的东西?

DynContextMenuBehavior.cs

public class DynContextMenuBehavior
{
 ...
    private void OnMenuOpened(object sender, RoutedEventArgs e)
    {
        ContextMenu.ItemsSource = ContextMenuHandler.GetMenuItems();
    }
}

DataTemplateResourceDictionary.xaml

...
<DataTemplate DataType="{x:Type viewmodels:MenuItemViewModel}">
    <views:MenuItemView />
</DataTemplate>
...

MenuItemView.xaml

<UserControl x:Class="ContextMenus.View.MenuItemView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:ContextMenus.View"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <MenuItem
        Style="{StaticResource style_MenutItem}"
        Header="{Binding Header}"
        Command="{Binding ClickCommand}" />
</UserControl>

MenuItemViewModel.cs

public class MenuItem : IMenuItem
{
...
}

修改

样式

<Style x:Key="style_MenutItem" TargetType="{x:Type MenuItem}">

</Style>

<Style x:Key="style_ContextMenu" TargetType="ContextMenu">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ContextMenu">
                <Border Name="Border" Margin="5" MinWidth="100" BorderThickness="1" Background="White">
                    <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

0 个答案:

没有答案