wpf - 相对源绑定(bind)表达式错误

标签 wpf mvvm relativesource

我正在使用 WPF RelativeSource BindingDataTemplate对于我的 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 的一些内容被触发VisibleHidden基于 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/

相关文章:

wpf - 如何在wpf中绘制交替颜色的曲线

c# - WPF 列表框样式

c# - MVVM : Share data between ViewModels

c# - 无法将简单的组合框与 mvvm 和 wcf ria 服务绑定(bind)

WPF 使用样式从嵌套元素中绑定(bind)到父属性

wpf - 来自 ToolTip 或 ContextMenu 的 RelativeSource 绑定(bind)

wpf - 将模型的变化列表同步到 ViewModel 的 ObservableList 的最佳实践?

c# - 发布应用程序时实体返回 null

java - 在ZK中,从其他ViewModel更改组件的属性

c# - 如何绑定(bind)ToolTip中的其他元素