基本上我有一个View,它绑定到一个具有MenuItems的ViewModel.
我想要做的是,每当菜单标题为“ – ”时,我想放置一个分隔符.
从理论上讲,我似乎可以避免使用TemplateSelectors,但如果您认为这是不可避免的,请分享这些解决方案.
这是XAML:
<Window x:Class="WpfApp1.MenuItemStyle"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MenuItemStyle" Height="300" Width="300">
<DockPanel>
<Menu DockPanel.Dock="Top" ItemsSource="{Binding MenuItems}">
<Menu.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<HierarchicalDataTemplate.Triggers>
<DataTrigger Binding="{Binding Title}" Value="-">
<Setter Property="ContentTemplate">
<Setter.Value>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<Separator />
</HierarchicalDataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</HierarchicalDataTemplate.Triggers>
<TextBlock Text="{Binding Title}" Background="Red" />
</HierarchicalDataTemplate>
</Menu.ItemTemplate>
</Menu>
<Grid>
</Grid>
</DockPanel>
</Window>
以下是代码背后的代码:
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MenuItemStyle.xaml
/// </summary>
public partial class MenuItemStyle : Window
{
public MenuItemStyle()
{
InitializeComponent();
this.DataContext = this;
}
public ObservableCollection<MenuItem> MenuItems { get; set; } = new ObservableCollection<MenuItem> {
new MenuItem{ Title = "M1"
,Children= new ObservableCollection<MenuItem>{
new MenuItem{ Title = "M2"},
new MenuItem{ Title = "-"},
new MenuItem{ Title = "M3"},
}
}
};
}
public class MenuItem
{
public string Title { get; set; }
public ObservableCollection<MenuItem> Children { get; set; }
}
}
我到处寻找解决方案,但找不到务实的解决方案.
最佳答案 您可以为MenuItem创建样式.使其成为具体菜单实例的本地(通过放置在菜单的Resources中)或将其放在资源字典中:
<Menu ItemsSource="{Binding MenuItems}">
<Menu.Resources>
<Style TargetType="MenuItem">
<Style.Triggers>
<DataTrigger Binding="{Binding Title}" Value="-">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Separator/>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Menu.Resources>
<Menu.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Title}" Background="Red" />
</HierarchicalDataTemplate>
</Menu.ItemTemplate>
</Menu>