我在DataTemplate中为我的一个ViewModel类使用了WPF RelativeSource Binding,如下所示:
<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视图上的一些东西是基于ViewModelA上的属性触发的Visible或Hidden。
这种方法工作得很好。
但是,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在实际的视图被释放之前被更新了。可以采取什么措施来修复此行为?
发布于 2015-04-13 16:43:37
我最终通过重写绑定逻辑修复了这段代码。绑定现在不再依赖于ViewModelA的属性。仍然有兴趣知道如何解决这样的问题。
https://stackoverflow.com/questions/29600881
复制相似问题