/ / UserControl要素の継承されたバインディングソースを設定します-wpf、xaml、data-binding

UserControl要素の継承バインディングソースを設定する - wpf、xaml、data-binding

本当に単純な構文の質問ですが、私はどこにも行きません:

(擬似コード)

MainWindow.xaml:

<grid>
<control:MyUserControl DataContext="{StaticResource MyDataSource}" />
</grid>

MyUserControl.xaml

<grid>
<stackpanel DataContext="{StaticResource MyOtherDataSource}" IsEnabled="{Binding Path=CanUseMe, Source={StaticResource MyDataSource}" />
</grid>

問題は {StaticResource MyDataSource} ユーザーコントロールにはこのリソースがないため、スタックパネルで。

スタックパネルのDataContextをすでに設定している場合、ソースバインディングをユーザーコントロールに渡される「グローバル」データソースに設定するにはどうすればよいですか?

ありがとう!

回答:

回答№1は1

UserControl"のDataContextはMyDataSourceになるため、次を使用できます。 RelativeSource このようなバインディングで

<grid>
<stackpanel DataContext="{StaticResource MyOtherDataSource}"
IsEnabled="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}},
Path=DataContext.CanUseMe}"/>
</grid>