2009-07-14 25 views
165

私は、ウィンドウに含まれるリスト(下記参照)を持っています。ウィンドウのDataContextには、2つのプロパティ、ItemsAllowItemCommandがあります。WPFデータバインディング:「親」データコンテキストにアクセスするにはどうすればよいですか?

HyperlinkCommandプロパティのバインドを取得するには、ウィンドウのDataContextを解決する必要がありますか?

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ... 
+0

デバッガに入ることができ、UIの構築時点まで進めることができますか?そうであれば、変数に入り、ドリルアップしようとすることができます –

+0

シンプルなソリューション(Windows 8 Store/Metroアプリケーションでも動作します)は、ここにあります:[http://stackoverflow.com/questions/15366609/how-to-access-両親 - datacontext-in-window-8-store-apps/15419382#15419382](http://stackoverflow.com/questions/15366609/how-to-access-parents-datacontext-in-window-8-store-apps/15419382#15419382) – LMK

答えて

331

あなたはこのような何かを試みることができます。私はこのような相対的なソースを使用し、それは正常に働いた。

RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"

+2

私はスタイル内からListBoxItemに設定されたContextMenuから自分のVM上のICommandにバインドするためにこれを使用しました。感謝しました! –

+1

Windows 8アプリではどうしますか? "ElementName = ..."を使用して動作させましたが、DataContextがリークします。 –

+3

リークの意味は? – flq

6

これはまた、シルバー5(おそらく以前にも私はそれをテストしていない)で動作します。

<ListView ItemsSource="{Binding Items}"> 
    <ListView.View> 
    <GridView> 
     <GridViewColumn Header="Action"> 
     <GridViewColumn.CellTemplate> 
      <DataTemplate> 
      <StackPanel> 
       <TextBlock> 

       <!-- this binding is not working --> 
       <Hyperlink Command="{Binding AllowItemCommand}" 
          CommandParameter="{Binding .}"> 
        <TextBlock Text="Allow" /> 
       </Hyperlink> 

       </TextBlock> 
      </StackPanel> 
      </DataTemplate> 
     </GridViewColumn.CellTemplate> 
     </GridViewColumn> 
    </GridView> 
    </ListView.View> 
</ListView> 
+0

なぜそれは良い考えではありませんか? – rolls

17

これも動作します:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, 
          Path=DataContext.AllowItemCommand}" /> 

ListViewWindowからそのDataContextを継承するので、それはあまりにも、この時点で利用可能です。
と同様のコントロール(例えば、Gridview,ListBoxなど)と同様に、ItemsControlのサブクラスであるため、このようなコントロールのBindingは完全に機能します。

関連する問題