我RelativeSource Binding在DataTemplate其中一个 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被触发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 会被更新。可以做些什么来解决这种行为?