【发布时间】:2017-08-19 06:50:20
【问题描述】:
我有一个树形视图,我想要一个右键单击菜单。单击菜单项时,应使用该项目调用命令。我尝试了不同的解决方案,但不断收到如下错误。
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression
我的树视图如下
<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>
也在视图模型中
private ICommand editCmd;
public ICommand EditCmd
{
get
{
if (editCmd == null)
editCmd = new DelegateCommand(EditObjectFunction);
return editCmd;
}
}
我尝试了不同的解决方案,例如This,但无法解决问题
【问题讨论】:
-
它没有树视图,我已经尝试了那里提供的解决方案。谢谢。
-
你试过 Path=Tag.EditCmd 吗?