每个绑定项目的子菜单 [英] Sub-menu for each binding item
问题描述
按照 Omer van Kloeten 的示例,我用我的可观察对象绑定的菜单项填充菜单收藏.我得到了一个用于单个集合项的菜单项.很好,但我实际上想要更多.我还希望能够有一个菜单项,其中包含一个集合项的两个或三个子项.这是一些粗略的草图:
Following the example from Omer van Kloeten I filled a menu with menu items bound from my observable collection. I got a single menu item for a single collection item. Fine, but I actually want more. I also want to be able to have a menu item with two or three sub items for one collection item. Here is some rough sketch:
What I Have What I Want
+ First Item + Create First Item
+ Second Item + Second Item
+ Delete
+ Update
此处First Item"具有属性Exists = false
,但Second Item"具有true
.我当前的代码:
Here "First Item" has property Exists = false
, but "Second Item" has it true
. My current code:
public class CollectionItem
{
public string Name { get; set; }
public bool Exists { get; set; }
}
public partial class MainWindow : Window
{
ObservableCollection<CollectionItem> items;
public MainWindow()
{
items = new ObservableCollection<CollectionItem>();
items.Add(new CollectionItem() { Name = "First Item", Exists = false });
items.Add(new CollectionItem() { Name = "Second Item", Exists = true });
AllItems.ItemsSource = items;
}
}
<MenuItem x:Name="AllItems" Header="What I Have">
<MenuItem.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Path=Name}" />
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
如何将简单的菜单项与子项混合在一起?
How do I mix simple menu items with sub items?
推荐答案
如何将简单的菜单项与子项混合在一起?
How do I mix simple menu items with sub items?
首先,您需要适当地构造数据,并使用集合属性来表示子项或子 MenuItem
.然后,您需要使用 MenuItem.ItemContainerStyle
将集合属性数据绑定到父 MenuItem
的 ItemsSource
属性,类似于您的现在正在做.你应该得到这样的结果:
First, you need to have your data structured appropriately, with collection properties to represent the child, or sub MenuItem
s. Then, you need to data bind the collection property to the ItemsSource
property of the parent MenuItem
using the MenuItem.ItemContainerStyle
, similar to what you're doing now. You should end up with something like this:
public class CollectionItem
{
public string Name { get; set; }
public bool Exists { get; set; }
public ObservableCollection<CollectionItem> CollectionOfSubItems { get; set; }
}
...
<MenuItem x:Name="AllItems" Header="What I Have">
<MenuItem.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Path=Name}" />
<Setter Property="ItemsSource" Value="{Binding CollectionOfSubItems}" />
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
这篇关于每个绑定项目的子菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!