次のように、ViewModel クラスの 1 つにWPF を使用してRelativeSource
Binding
います。DataTemplate
<DataTemplate x:Type="{x:Type ViewModelB}">
<Grid Visibility="{Binding DataContext.MyBoolProperty,
RelativeSource={RelativeSource AncestorType=ContentControl},
Converter={StaticResource BooleanToVisibilityConverter}}">
</Grid>
</DataTemplate>
ルート ViewModel にViewModelA
は、この ViewModel のインスタンスがパブリック プロパティとしてありDataTemplate
、次のようにそのためのもあります。
<DataTemplate x:Type="{x:Type ViewModelA}">
<ContentPresenter Content="{Binding ViewModelBProperty}" />
</DataTemplate>
ご覧のとおり、ViewModelB
トリガーされるVisible
かHidden
、 on のプロパティに基づいて、ビューにいくつかのものが必要ViewModelA
です。
このアプローチはうまく機能します。
ただし、ViewModelA
それ自体は にも示されていContentPresenter
ます。この内容を変更するとContentPresenter
(例: にViewModelC
)、デバッグ ログに次のようなバインド例外が表示されます。
System.Windows.Data Error: 40 : BindingExpression path error: 'MyBoolProperty' property not found on 'object' ''ViewModelC' (HashCode=56562781)'. BindingExpression:Path=DataContext.MyBoolProperty; DataItem='ViewModelC' (Name=''); target element is 'Grid' (Name=''); target property is 'Visibility' (type 'Visibility')
Binding
ここでは、実際のビューが破棄される前に DataContext が更新されると推測しています。この動作を修正するにはどうすればよいですか?