Wpf TreeViewItem上下文菜单命令绑定不起作用



我想为TreeViewItems创建一个ContextMenu,并传递一个参数作为TreeViewItem数据上下文(而不是TreeView数据上下文(。

我收到下面的命令绑定错误。问题出在哪里?我还尝试了TreeViewItemMenuItemContextMenu作为AncestorType。我还尝试了AncestorLevel作为123,但没有改变结果。

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绑定不起作用。

TreeViewItemTag属性绑定到父TreeViewDataContext。然后,您可以通过上下文菜单上的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>

相关内容

  • 没有找到相关文章

最新更新