2010-04-24 1 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-of-contextmenu 명령. 그 답이 당신의 문제를 해결합니까? – Andy

답변

1

문제점은 자원에서의 바인딩 사용과 관련이 있습니다. {Binding Path=Value,Source={x:Static Some.StaticProperty}}과 같은 것을 사용하지 않으면 정상적으로 작동하지 않습니다. ElementName 또는 DataContext 바인딩이 작동하려면 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>