I have a treeview and i want have a menu on right click. On clicking menu item a command should get called with the item. I have tried different solution but keep getting error as below.
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression
My treeview is as below
<TreeView ItemsSource="{Binding Buildings}" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" Grid.RowSpan="4">
<TreeView.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Gates}" DataType="{x:Type local:Floor}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Floors}" DataType="{x:Type local:Building}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" >
<TextBlock.ContextMenu>
<ContextMenu>
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.EditCmd}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:Gate}">
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</TreeView.Resources>
</TreeView>
Also in viewmodel
private ICommand editCmd;
public ICommand EditCmd
{
get
{
if (editCmd == null)
editCmd = new DelegateCommand(EditObjectFunction);
return editCmd;
}
}
I have tried different solution like This but could not solve the problem