简体   繁体   English

将命令绑定到MenuItem

[英]Bind Command to MenuItem

I have ListView and i am trying to bind command to ContextMenu of ListView. 我有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}" />

Binding to Button works well but when i click to delete item in ContextMenu, command is not working! 绑定到Button效果很好,但是当我单击以删除ContextMenu中的项目时,命令不起作用! Why? 为什么?

Your problem is related to using bindings in resources. 您的问题与在资源中使用绑定有关。 They normally don't work unless you are using something like {Binding Path=Value,Source={x:Static Some.StaticProperty}} . 除非您使用{Binding Path=Value,Source={x:Static Some.StaticProperty}}类的东西,否则它们通常不起作用。 In order for ElementName or DataContext bindings to work you need to resort to help of ElementSpy and DataContextSpy . 为了使ElementNameDataContext绑定起作用,您需要借助ElementSpyDataContextSpy帮助。 In your particular case if you are relying on DataContext binding, your XAML should look like this: 在特定情况下,如果您依赖于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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM