2011-11-18 2 views
2

WPF를 처음 사용합니다. 다른 많은 사람들과 마찬가지로 ContextMenuObservableCollection에 바인딩하여 동적 컨텍스트 메뉴를 만들려고합니다. 메뉴 항목을 나타내는 MenuItemViewModel 클래스의 TheCommand 속성에 Command 속성을 바인딩하는 것을 제외하면 모두 작동합니다. 이 명령은 실행되지 않습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?동적 MVVM 컨텍스트 메뉴에서 명령 바인딩이 작동하지 않습니다.

처음부터 시작하려면 ContextMenuImage의 하위이며 마우스가 Image 위에있을 때 표시됩니다. 빈의 ContextMenu는 다음과 같이 정의된다

<Image.ContextMenu > 
     <ContextMenu ItemsSource="{DynamicResource ContextMenu}" 

은 다음과 같습니다

<Window.Resources> 
    <local:MenuItemViewModelCollection x:Key="ContextMenu"> 
    </local:MenuItemViewModelCollection> 

    <HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}" 
             ItemsSource="{Binding Path=Children}"> 
     <HierarchicalDataTemplate.ItemContainerStyle> 
      <Style TargetType="MenuItem"> 
       <Setter Property="Command" 
        Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, 
            Path=DataContext.TheCommand}"/> 
       <!-- Value="{Binding Path=TheCommand}" /> I tried this too --> 

      </Style> 
     </HierarchicalDataTemplate.ItemContainerStyle> 
    </HierarchicalDataTemplate> 
</Window.Resources> 

TheCommand 속성은 아래에 정의되어

public class MenuItemViewModel : INotifyPropertyChanged 
{ 
     //... 
     public ICommand TheCommand 
     { 
      //... 
     } 
} 
+0

'MenuItemViewModelCollection' 클래스는 어떻게 생겼습니까? 메뉴 항목이 올바르게 표시됩니까? – Rachel

답변

0

당신이

Value="{TemplateBinding TheCommand}"

을 시도 했습니까?

+1

네, 고마워요. 그것은 또한 작동하지 않습니다 – Marianna

4

ContextMenus의 DataContext가 이상 할 수 있습니다. 디버깅 할 때 Visual Studio의 출력 창에서 TheCommand를 찾을 수 없다는 바인딩 오류가있는 것을 보면 알 수 있습니다. 다음보십시오 :

<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.DataContext.TheCommand}"/> 

이것은의 ContextMenu 컨텍스트 메뉴 자체를하지에서 시작되는 요소의 DataContext를 사용합니다. 다음과 같은 질문에 대한 내 대답에

+0

이것은 정확하게 내가 고치려고 노력하고 출력 창의 팁이 매우 도움이됩니다. 그러나 DataContext가 선택되는 계층 구조를 이해할 수는 없습니다. 때문에 내 경우에 그것은 콘텐츠를 데리러 왔어 'Content = "{Binding Heading}" 그러나 명령을 수령하지 못했습니다.Command = "{Binding DataContext.ItemSelectedCommand}" 그래서 나는 사용 했음 'Command = "{Binding RelativeSource = {RelativeSource AncestorType = {x : 유형 ContextMenu}}, Path = DataContext.ItemSelectedCommand}"' – CarbineCoder

관련 문제