0

I have a TreeView with ContextMenu, and inside that menu I want to bind to a command on VIewModel

<TreeView x:Name="treeView"
          ItemTemplate="{StaticResource ItemTemplate}"
          ItemsSource="{Binding View}">

    <TreeView.ContextMenu>
        <ContextMenu>
            <telerik:RadMenuItem Header="Remove" Command="{Binding RemoveCommand}" CommandParameter="{Binding ElementName=treeView, Path=SelectedItem, Mode=OneWay}" />
        </ContextMenu>
    </TreeView.ContextMenu>
</TreeView>

I receive an exception in Output window, like

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=treeView'. BindingExpression:Path=SelectedItem; DataItem=null; target element is 'RadMenuItem' (Name=''); target property is 'CommandParameter' (type 'Object')

I am actually using RadTreeView, but the same applies for TreeView. Why I cannot bind to TreeView's SelectedItem property? I have tried with RelativeSource AncestorType, the same problem.

4

1 回答 1

2

问题是,就像 Popup 控件一样,它是一个不同的可视化树。该错误告诉您它正在尝试在“ CommandParameter”上查找名为“ ”的属性RadMenuItem,因为这是它在 ContextMenu 的可视化树中的 DataContext。

这将帮助您:展示位置目标

我最终CommandTarget将 MenuItem 的属性设置为 ContextMenu 的PlacementTarget属性,但它看起来不像您正在采用的方法。即便如此,这PlacementTarget就是您正在寻找的东西。

于 2012-05-23T01:21:53.267 回答