将命令绑定到MenuItem

时间:2010-04-24 21:17:23

标签: c# wpf xaml command

我有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}" />

绑定到按钮效果很好但是当我单击以删除ContextMenu中的项目时,命令不起作用!为什么呢?

1 个答案:

答案 0 :(得分:1)

您的问题与在资源中使用绑定有关。除非您使用{Binding Path=Value,Source={x:Static Some.StaticProperty}}之类的内容,否则它们通常无法正常工作。要使ElementNameDataContext绑定有效,您需要求助于ElementSpyDataContextSpy。在您的特定情况下,如果您依赖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>