2010-04-24 125 views
0

我有ListView,我試圖將命令綁定到ListView的ContextMenu。綁定命令到MenuItem

<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中的項目,命令不工作!爲什麼?

+0

可能類似的問題:http://stackoverflow.com/questions/911904/commandbinding-in-window-doesnt-catch -execution-的命令從 - 文本菜單。這個答案能解決你的問題嗎? – Andy 2010-04-24 23:47:01

回答

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>