I am trying to bind the commandParamater of my ContextMenu item to another element on the form, however no matter what I try the commandParamater is always null.
Can someone please show me how to correctly bind the commandParamater of my context menu item?
What I have:
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Files}">
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Rename Folder"
Command="{Binding Path=ToggleControlVisability}"
CommandTarget="{Binding ElementName=FolderEditor}"
CommandParameter="{Binding ElementName=FolderEditor}">
</MenuItem>
</ContextMenu>
</Grid.ContextMenu>
<Label Content="{Binding Path=FolderName}"></Label>
<StackPanel Name="FolderEditor" Orientation="Horizontal"
Visibility="Hidden">
<TextBox Text="{Binding Path=FolderName}"></TextBox>
</StackPanel>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
This is a very common problem encountered in WPF; Context menu itself is not part of the same visual tree as the control it was defined on, due to this it’s not possible to use
ElementNameorRelativeSourcebindings.I have also faced this issue recently and solution using Tag and
PlacementTargetworked fine for me.Here are some posts having different solutions to this problem(apart from one CodeNaked suggested) –
How to set CommandTarget for MenuItem inside a ContextMenu?
http://www.sevensteps.com/binding-contextmenu-commands-in-wpf-to-the-controls-viewmodel.ashx
http://www.ikriv.com/blog/?p=434