1

次のように、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トリガーされるVisibleHidden、 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 が更新されると推測しています。この動作を修正するにはどうすればよいですか?

4

1 に答える 1

0

バインディングロジックをまとめて書き直すことで、このコードを修正しました。バインディングは、ViewModelA のプロパティに依存しなくなりました。そのような問題をどのように解決できるかを知りたいと思っています。

于 2015-04-13T08:43:36.700 に答える