2011-01-20 140 views
2

我想使用MVVM將ObservableCollection綁定到ContextMenu。但是當我嘗試發射命令時,什麼都沒有發生。另外,我需要將字符串作爲命令參數傳遞給事件。WPF MVVM ContextMenu綁定到ObservableCollection <string>不命中命令

下面是XAML代碼:

<ContextMenu Name="ctxAddApplication" ItemsSource="{Binding Path=ApplicationTypes}"> 
    <ContextMenu.ItemContainerStyle> 
    <Style TargetType="{x:Type MenuItem}"> 
     <Setter Property="Command" Value="{Binding AddRequirementCommand}"/> 
     <Setter Property="CommandParameter" Value="{Binding}"/> 
    </Style> 
    </ContextMenu.ItemContainerStyle> 
</ContextMenu> 

下面是視圖模型代碼:

public ObservableCollection<string> ApplicationTypes { get; private set; } 

public ComposableCommand AddRequirementCommand { get; private set; } 

this.AddRequirementCommand = new ComposableCommand(this.AddRequirementView); 

private void AddRequirementView(object applicationName) {} 

請幫助!

+0

請格式化的XAML。這種方式很難閱讀。 – 2011-01-20 10:08:12

回答

2

以防萬一你需要的代碼:

<ContextMenu Name="ctxAddApplication" ItemsSource="{Binding Path=ApplicationTypes}"> 
       <ContextMenu.ItemContainerStyle> 
        <Style TargetType="{x:Type MenuItem}"> 
         <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=DataContext.AddRequirementCommand}"/> 
         <Setter Property="CommandParameter" Value="{Binding}"/> 
        </Style> 
       </ContextMenu.ItemContainerStyle> 
      </ContextMenu> 
+0

非常感謝,如果工作... – Arihant 2011-01-20 10:24:17

0

每個項目的ContextMenu視圖內都綁定到集合中的項目。

<Setter Property="Command" Value="{Binding AddRequirementCommand}" /> 

這將嘗試在字符串類中找到'AddRequirementCommand'。在這個綁定中使用RelativeSource。還可以使用VS調試器和輸出窗口查看綁定錯誤,它通常有很多幫助。

2

每個菜單項的數據上下文將是它綁定的任何內容。在你的情況下,一個字符串,因爲你的ApplicationTypes屬性是一個字符串的集合。因此,您設置命令的綁定將不起作用,因爲類型String上沒有AddRequirementCommand屬性。