在DataTemplate中为MenuItem指定命令 [英] Specify Command for MenuItem in a DataTemplate
问题描述
我有一个上下文菜单。它绑定到一些集合,它有一个定义的ItemTemplate,像这样:
I have a context menu. It's bound to some collection and it has a defined ItemTemplate like this:
<ContextMenu
ItemsSource={Binding ...}
ItemTemplate={StaticResource itemTemplate}
/>
itemTemplate是一个带有TextBlock的简单DataTemplate:
itemTemplate is a simple DataTemplate with a TextBlock:
<DataTemplate x:Key="itemTemplate">
<TextBlock Text={Binding ...} />
</DataTemplate>
如何将MenuItem的Command属性绑定到底层对象的属性?
How do I bind Command property for MenuItem to the underlying object's property?
推荐答案
我想你需要将你的TextBlock包装在一个MenuItem中:
I think you need to wrap your TextBlock in a MenuItem:
<DataTemplate x:Key="itemTemplate">
<MenuItem Command={Binding ...}>
<TextBlock Text={Binding ...} />
</MenuItem>
</DataTemplate>
但我现在没有一个IDE在我面前试试这个。让我知道它是怎么回事。
But I don't have an IDE in front of me right now to try this. Let me know how it goes.
看起来你需要使用ItemContainerStyle,如下所示此处。对不起,引导你开始错误的路径,但我在一个IDE的前面,这工作:
Looks like you need to use the ItemContainerStyle as seen here. Sorry for leading you down the wrong path at the start there - but I got in front of an IDE and this works:
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding ...}"/>
</Style>
</ContextMenu.ItemContainerStyle>
这篇关于在DataTemplate中为MenuItem指定命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!