我正在使用 WPF RelativeSource
Binding
在 DataTemplate
对于我的 ViewModel 类之一,如下所示:
<DataTemplate x:Type="{x:Type ViewModelB}">
<Grid Visibility="{Binding DataContext.MyBoolProperty,
RelativeSource={RelativeSource AncestorType=ContentControl},
Converter={StaticResource BooleanToVisibilityConverter}}">
</Grid>
</DataTemplate>
一个 Root View 模型,
ViewModelA
,具有此 ViewModel 的实例作为公共(public)属性,并且还具有 DataTemplate
为此,像这样: <DataTemplate x:Type="{x:Type ViewModelA}">
<ContentPresenter Content="{Binding ViewModelBProperty}" />
</DataTemplate>
如您所见,我想要查看
ViewModelB
的一些内容被触发Visible
或 Hidden
基于 ViewModelA
上的属性.这种方法效果很好。
但是,
ViewModelA
本身也在 ContentPresenter
中出现.当我更改此 ContentPresenter
的内容时(例如到 ViewModelC
),我的调试日志中出现了一些绑定(bind)异常,例如: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 在实际 View 被释放之前得到更新。可以做些什么来解决这种行为?
最佳答案
我最终通过重新编写绑定(bind)逻辑来修复此代码。绑定(bind)现在不再依赖于 ViewModelA 的属性。仍然有兴趣知道如何解决这样的问题。
关于wpf - 相对源绑定(bind)表达式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29600881/