![](/img/trans.png)
[英]WPF MenuItem: How to bind a SubMenuItem command to to its Parent MenuItem
[英]Bind Command to MenuItem
我有ListView,我想将命令绑定到ListView的ContextMenu。
<ListView x:Name="listView1" ItemsSource="{Binding Path=Persons}">
<ListView.Resources>
<ContextMenu x:Key="ItemContextMenu">
<MenuItem Header="Add" />
<MenuItem Header="Edit"/>
<Separator/>
<MenuItem Header="Delete" Command="{Binding Msg}" />
</ContextMenu>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<!--<EventSetter Event="PreviewMouseLeftButtonDown" />--><!--Handler="OnListViewItem_PreviewMouseLeftButtonDown" />-->
<Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}" />
<GridViewColumn Header="Sur Name" DisplayMemberBinding="{Binding Path=SurName}" />
<GridViewColumn Header="Age" DisplayMemberBinding="{Binding Path=Age}" />
</GridView>
</ListView.View>
</ListView>
<Button Content="Message" Command="{Binding Msg}" />
绑定到Button效果很好,但是当我单击以删除ContextMenu中的项目时,命令不起作用! 为什么?
您的问题与在资源中使用绑定有关。 除非您使用{Binding Path=Value,Source={x:Static Some.StaticProperty}}
类的东西,否则它们通常不起作用。 为了使ElementName
或DataContext
绑定起作用,您需要借助ElementSpy
和DataContextSpy
帮助。 在特定情况下,如果您依赖于DataContext
绑定,则XAML应该如下所示:
<ListView.Resources>
<DataContextSpy x:Name="spy" />
<ContextMenu x:Key="ItemContextMenu">
<MenuItem Header="Add" />
<MenuItem Header="Edit"/>
<Separator/>
<MenuItem Header="Delete" Command="{Binding DataContext.Msg,Source={StaticResource spy}}" />
</ContextMenu>
</ListView.Resources>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.