我想为TreeViewItem
s创建一个ContextMenu
,并传递一个参数作为TreeViewItem
数据上下文(而不是TreeView
数据上下文(。
我收到下面的命令绑定错误。问题出在哪里?我还尝试了TreeViewItem
、MenuItem
和ContextMenu
作为AncestorType
。我还尝试了AncestorLevel
作为1
、2
、3
,但没有改变结果。
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TreeView', AncestorLevel='1''. BindingExpression:Path=DataContext.DeleteFolderCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')
这是我的代码:
<TreeView ItemsSource="{Binding Folders}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}"
BasedOn="{StaticResource {x:Type TreeViewItem}}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Sil"
Command="{Binding DataContext.DeleteFolderCommand,RelativeSource={RelativeSource AncestorType={x:Type TreeView},Mode=FindAncestor}}"
CommandParameter="{Binding }"></MenuItem>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
ContextMenu
与其关联的控件不属于同一可视树,因此RelativeSource
绑定不起作用。
将TreeViewItem
的Tag
属性绑定到父TreeView
的DataContext
。然后,您可以通过上下文菜单上的PlacementTarget
属性访问此属性,该属性设置为相应的TreeViewItem
。
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}"
BasedOn="{StaticResource {x:Type TreeViewItem}}">
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"/>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Sil"
Command="{Binding PlacementTarget.Tag.DeleteFolderCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}"></MenuItem>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</TreeView.ItemContainerStyle>