2016-09-21 7 views
1

私は、次のレイアウト持っているにバインドするのMenuItemコマンド:なしの成功とツリービューアイテムのコンテキスト内からのUserControlのViewModelのコマンドを呼び出そうとのUserControlのDataContext

public class ParentUserControl : UserControl{...} 

<ParentNameSpace:ParentUserControl 
... 
DataContext={Binding MyViewModel ....} 
> 
<TreeView ...>     
<HierarchicalDataTemplate  
     .... > 
       <StackPanel> 
        <StackPanel.ContextMenu> 
         <ContextMenu> 
          <MenuItem Header="item" 
          Command="{Binding DataContext.SomeCommandInMyViewModel, 
           RelativeSource={RelativeSource 
           AncestorType={x:Type ParentUserControl}}}"/> 
         </ContextMenu> 
        </StackPanel.ContextMenu> 
        <TextBlock Text="{Binding Path=Name}"/> 
       </StackPanel> 
      </HierarchicalDataTemplate> 
</TreeView> 

イムを。 ParentUserControlはwpfプロジェクトではサポートされていません。 AncestorTypeをUserControlに変更すると、コマンドは呼び出されません。私が見逃しているものはありますか?

答えて

0

これは、ContextMenuがビジュアルツリーの一部ではないためです。

ParentUserControlに名前を付けます:コードビハインド変更することなく、最も簡単な方法は、これがこのバインディング

<ParentNameSpace:ParentUserControl x:Name="ParentRoot" ... > 

用途:x:Name属性なしで使用するための

Command="{Binding Source={x:Reference Name=ParentRoot}, Path=DataContext.SomeCommandInMyViewModel}" 

更新

ContextMenu.PlacementTargetプロパティを使用できます。この場合、StackPanelが指定されています。次に、あなたのビューモデルにアクセスするためのプロパティーをTagで使用できます。

<StackPanel Tag="{Binding RelativeSource={RelativeSource AncestorType=ParentNameSpace:ParentUserControl}, Path=DataContext}"> 

とコマンド:

Command="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.Tag.SomeCommandInMyViewModel}" 
+0

私の基底クラスは抽象的で、原因となる単一パラメータのコンストラクタで別の抽象クラスから派生: を型「ParentUserControlは、」名前の属性を持つことはできません。既定のコンストラクタのない値の型と型は、ResourceDictionary内の項目として使用できます。 Baseクラスを変更したくない場合は、これを解決する別のアイデアがありますか?/? – Milleu

+0

@Milleu答えを更新しました。 – Sam

+0

素晴らしい感謝!、それは動作します!私の理解のために - 別のビジュアルツリー(異なるプロセスや何か)でContextMenu内の祖先を使うことができませんでしたので、ViewModelにアクセスするためにタグ(または名前)を定義する必要があります。私はいくつかのHierachicalDataTemplatesをTreeviewでタグを一度定義できますか?タグは常に所有者要素で定義する必要がありますか?(TreeViewにタグを移動してAncestorTypeをTreeViewに変更しても成功しませんでした) – Milleu

関連する問題