RelativeSource BindingExpression错误

时间:2015-04-13 08:24:18

标签: wpf mvvm relativesource

我在RelativeSource中为我的一个ViewModel类使用了WPF 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触发HiddenViewModelA的视图中找到一些内容。

这种方法很好用。

但是,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')

我在这里猜测,在放置实际视图之前,DataContext的Binding会更新。如何解决此问题?

1 个答案:

答案 0 :(得分:0)

我最后通过重写绑定逻辑来修复此代码。绑定现在不再依赖于ViewModelA的属性。仍然有兴趣知道如何解决这样的问题。

相关问题