1

RelativeSource BindingDataTemplate其中一个 ViewModel 类中使用 WPF,如下所示:

<DataTemplate x:Type="{x:Type ViewModelB}">
     <Grid Visibility="{Binding DataContext.MyBoolProperty, 
                        RelativeSource={RelativeSource AncestorType=ContentControl}, 
                        Converter={StaticResource BooleanToVisibilityConverter}}">
     </Grid>
</DataTemplate>

根 ViewModelViewModelA具有此 ViewModel 的一个实例作为公共属性,并且还有一个DataTemplate用于它的实例,如下所示:

  <DataTemplate x:Type="{x:Type ViewModelA}">
      <ContentPresenter Content="{Binding ViewModelBProperty}" />
  </DataTemplate>

如您所见,我希望 View 上有一些东西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 回答