我有一個窗口,裏面有一個treeview。該窗口有一個視圖模型,樹視圖項來自我的視圖模型。從itemcontainerstyle找到commandparameter的datacontext
我有一個我的treeview的contextmenu,它是基於在treeview上做出的選擇而動態生成的。我在我的viewmodel中有一個屬性,樹視圖上的所有選定節點都正確填充。
我的動態生成的contextmenuitems綁定到一個命令,命令參數來自我的viewmodel或我的主窗口datacontext。我試圖在我的contextmenu itemcontainerstyle中設置命令參數綁定,但它一直抱怨它無法找到上下文。
這是我的xaml代碼,位於我的MainWindow中。現在
<TreeView ItemsSource="{Binding Nodes}" x:Name="treeView">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<StackPanel>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
<TreeView.ContextMenu>
<ContextMenu ItemsSource="{Binding MenuItems}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Header" Value="{Binding Name}"/>
<Setter Property="Command" Value="{Binding MenuItemCommand}"/>
<Setter Property="CommandParameter" Value="{Binding Path=DataContext.SelectedModels}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</TreeView.ContextMenu>
</TreeView>
我的視圖模型:
public class MyViewModel:NotificationObject
{
private readonly IMenuRepository _menuRepository;
public MyViewModel(IMenuRepository menuRepository)
{
_menuRepository = menuRepository;
}
private ObservableCollection<string> _nodes;
public ObservableCollection<string > Nodes
{
get { return _nodes; }
set
{
_nodes = value;
RaisePropertyChanged(() => Nodes);
}
}
private ObservableCollection<string> _selectedModels;
public ObservableCollection<string> SelectedModels
{
get { return _selectedModels; }
set
{
_selectedModels = value;
RaisePropertyChanged(() => SelectedModels);
}
}
public ObservableCollection<MyMenuItem> MenuItems
{
get {return _menuRepository.GetAll(SelectedModels); }
}
}
..和我的菜單項視圖模型
public class MyMenuItem:NotificationObject
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged(() => Name);
}
}
private DelegateCommand<IEnumerable<string>> _menuItemCommand;
public DelegateCommand<IEnumerable<string>> MenuItemCommand
{
get { return _menuItemCommand; }
set
{
_menuItemCommand = value;
RaisePropertyChanged(() => MenuItemCommand);
}
}
}
菜單項得到正確生成,並且該命令被正確地結合爲好。然而,命令是灰色的,我可以看到在我的輸出窗口中的錯誤,說:
System.Windows.Data Error: 39 : BindingExpression path error: 'DataContext' property not found on 'object' ''DeleteMenuItem' (HashCode=20916652)'. BindingExpression:Path=DataContext.SelectedModels; DataItem='DeleteMenuItem' (HashCode=20916652); target element is 'MenuItem' (Name=''); target property is 'CommandParameter' (type 'Object')
能否請你告訴我如何正確綁定呢?
注意:我認爲這是綁定,但即使綁定設置得當,菜單項也會灰顯。你能幫忙嗎?該框架是.NET 3.5
感謝, -Mike