I have a TreeView created using HierarchicalDataTemplate with help of this famous article.
Each node in my treeview has a different contextMenu. So I created a property for treeView that return for me the object of every node selected. Then I used the code below to display my ContextMenu. But the contextMenu is always empty.
<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: (No relation with 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 });
}
I believe I'm missing something in relation with binding.
NB: when debugging, I found in xaml that the value of ContextMenuMap changed as expected but always nothing is displayed.