【发布时间】:2015-11-25 21:35:09
【问题描述】:
在这个著名的article 的帮助下,我使用 HierarchicalDataTemplate 创建了一个 TreeView。
我的树视图中的每个节点都有不同的 contextMenu。因此,我为 treeView 创建了一个属性,该属性为我返回所选每个节点的对象。然后我使用下面的代码来显示我的 ContextMenu。但 contextMenu 始终为空。
<view:MyTreeView ItemsSource="{Binding MyNode}"
SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}" >
<TreeView.Resources>
<ContextMenu x:Key="MyContextMenu" ItemsSource="{Binding ContextMenuItem}"/>
<DataTemplate DataType="{x:Type local:ChildViewModel}">
<StackPanel Orientation="Horizontal" ContextMenu="{StaticResource MyContextMenu}">
//...
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</view:MyTreeView>
PrincipalViewModel:(与 ChildViewModel 无关)
private ICommand _editMapCommand;
public ICommand EditMapCommand
{
get
{
return _editMapCommand;
}
set
{
SetProperty(ref _editMapCommand, value, () => EditMapCommand);
OnPropertyChanged("EditMapCommand");
}
}
private ICommand _removeMapCommand;
public ICommand RemoveMapCommand
{
get
{
return _removeMapCommand;
}
set
{
SetProperty(ref _removeMapCommand, value, () => RemoveMapCommand);
OnPropertyChanged("RemoveMapCommand");
}
}
private ObservableCollection<MenuItem> _contextMenuMap;
public ObservableCollection<MenuItem> ContextMenuMap
{
get
{
return _contextMenuMap;
}
set
{
SetProperty(ref _contextMenuMap, value, () => ContextMenuMap);
OnPropertyChanged("ContextMenuMap");
}
}
private object _selectedItem;
public object SelectedItem
{
get
{
return _selectedItem;
}
set
{
SetProperty(ref _selectedItem, value, () => SelectedItem);
OnPropertyChanged("SelectedItem");
Fill(_selectedItem);
}
}
private void FillPropertyCard(object obj)
{
PcEditable = false;
if (obj is MyObject)
{
ContextMenuMap = new ObservableCollection<MenuItem>();
EditMapCommand = new DelegateCommand<CancelEventArgs>(OnEditMapCommandExecute, OnEditMapCommandCanExecute);
RemoveMapCommand = new DelegateCommand<CancelEventArgs>(OnRemoveMapCommandExecute, OnRemoveMapCommandCanExecute);
ContextMenuMap.Add(new MenuItem() { Header = "editHeader", Command = EditMapCommand });
ContextMenuMap.Add(new MenuItem() { Header = "removeHeader", Command = RemoveMapCommand });
}
我认为我缺少与绑定相关的内容。
注意:调试时,我在 xaml 中发现 ContextMenuMap 的值按预期发生了变化,但始终没有显示任何内容。
【问题讨论】:
标签: wpf xaml mvvm treeview contextmenu