2011-11-18 97 views
2

我是WPF的新手。像其他許多人一樣,我試圖將ContextMenu綁定到ObservableCollection以創建動態上下文菜單。 除了將Command屬性綁定到代表菜單項的MenuItemViewModel類的TheCommand屬性之外,所有內容均可正常工作。該命令未被解僱。我究竟做錯了什麼?命令綁定在動態MVVM中不起作用上下文菜單

要從頭開始,ContextMenuImage的孩子,並且在鼠標位於Image上時顯示。

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

這將使用該文本菜單是從,沒有上下文菜單本身發起的元素的DataContext的。

+0

這正是我試圖解決的問題,輸出窗口上的提示非常有幫助。但是我無法理解DataContext被拾取的層次結構。因爲在我的情況下,它正在拾取這樣的內容,但它不能拾取命令 'Content =「{Binding Heading}」 「我必須使用 'Command =「{Binding RelativeSource = {RelativeSource AncestorType = {x:Type ContextMenu}},Path = DataContext.ItemSelectedCommand}'' – CarbineCoder