WPF:向数据绑定动态菜单中的每个菜单项添加命令
如何向数据绑定菜单中的每个项目添加命令?基本上,我有这样的内容:
<MenuItem Header="View" ItemsSource="{Binding ...}" />
对于菜单中的每个项目,我需要根据其 DataContext 为其提供一个命令。我无法使用 ItemTemplate,因为模板位于生成的 MenuItem 容器内。哦,命令需要有输入手势,所以需要在菜单打开之前生成。
有更好的方法吗?也许我应该添加/删除代码隐藏中的项目?
How can I add a command to each item in a data-bound menu? Basically, I have something like this:
<MenuItem Header="View" ItemsSource="{Binding ...}" />
For each item in the menu, I need to give it a Command based on its DataContext. I can't use the ItemTemplate since the template is inside the generated MenuItem container. Oh, and the commands need to have input gestures, so they need to be generated before the menu is opened.
Is there a better way to do this? Maybe I should add/remove the items in code-behind?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请记住,MenuItem(和 Menu)只是 ItemsControl。这意味着您可以将任何内容的集合绑定到它。换句话说,您可以将其绑定到具有 ICommand 的任何集合(也称为您的视图模型)。
但我们不想要这样,我们想要 MenuItems,对吗?因此,您可以做的就是将要绑定的集合设置为您在幕后创建的 MenuItems 集合。
然而,如果我们可以帮助的话,我们并不真的希望在代码隐藏中实例化控件。它导致可测试性较差并且通常很笨重。
因此,我们可以做的是绑定到您的业务对象的集合,但使用 < em>自定义 TypeConverter 将该列表转换为正确绑定到每个对象的 MenuItem 列表。
这种方法的真正好处是,无论菜单结构有多深,它都可以工作。类型转换器可以遍历您的视图模型并递归地添加新的绑定,这些绑定又使用相同的类型转换器
另一种选择是为您的菜单项视图模型创建一个 DataTemplate,该视图模型又包含一个 MenuItem,但我不完全确定如何使用它来处理手势方法。但这可能是可能的,并且该方法也是递归的。
Remember that MenuItem (and Menu) are just ItemsControls. This means that you can bind a collection of anything to it. In other words you can bind it to a collection of whatever has the ICommand on it (aka, your viewmodel).
But we dont want that, we want MenuItems right? So what you can do is make the collection you're binding to a collection of MenuItems that you create behind the scenes.
However we dont really want to have controls instanciated in the codebehind if we can help it. It leads to poor testability and is genereally clunky.
So what we can do instead is bind to a collection of your buisness objects but use a custom TypeConverter to convert that list into a list of MenuItems that are correctly bound to each object
Whats really nice about this approach is that it works no matter how deep you menu structure is. The Typeconverter can walk though your viewmodel and recursivly add new bindings that in turn use the same type converter
Another option is to create a DataTemplate for your menu item viewmodel that in turn contains a MenuItem, but im not entirely sure how to handle gestures using that approach. it might be possible though and that approach is also recursive.