1

TreeView に ContextMenu があります

UserControl (DataContext=ViewModel)
    |
    |
    ---- TreeView (ItemSource=MyItems)
           |
           |
           ----- Items (ItemSource=MyChildrenItems)
                   |
                   |
                   ----- ContextMenu

ContextMenuItem の Command を ViewModel の RelayCommand にバインドしたいのですが、あらゆる種類の RelativeSource バインディングを試しましたが、何もうまくいかないようです...

RelativeSource バインディングはどのように構成すればよいですか?

<ContextMenu>
    <MenuItem
        Header="Bla"
        Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=TreeView}, Path=DataContext.MyRelayCommand}" />

次のようなバインディングエラーが発生します

参照 'RelativeSource FindAncestor、AncestorType='System.Windows.Controls.TreeView'、AncestorLevel='1'' でバインディングのソースが見つかりません。BindingExpression:Path=DataContext.ExcludeSeasonCommand; DataItem=null; ターゲット要素は 'MenuItem' (Name='') です。ターゲット プロパティは 'Command' (タイプ 'ICommand') です。

4

2 に答える 2

2

最後に、何度も何度もGoogle検索を行った後、私は解決策に出くわしました

<MenuItem
    Header="Exclude season"
    Command="{Binding DataContext.MyRelayCommand, Source={x:Reference _myTreeView}}" />

HierarchicalDataTemplate はビジュアル ツリーに表示されないため、「相対」ソースはありません...

私はこれが彼/彼女の髪を引っ張っている他の誰かを助けることを願っています...

于 2014-10-06T19:51:51.583 に答える
1

別の一般的に使用されるソリューション:

<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext}" />
于 2014-10-06T20:28:25.107 に答える