绑定到子项属性

4

我有一些带有视图模型的页面。使用 Frame.NavigationManager.Navigate() 方法,将一个 Page 显示在 Frame 中。

在其中一个 Page 页面中,我有一个包含子元素 DataGridGroupBox。我想要根据 DataGrid 中的项目数量更改 GroupBox 的可见性。

以下是我的代码:

<GroupBox ....
          Visibility="{Binding ElementName=SomeDataGrid,
                                   Path=HasItems,
                                   Converter={StaticResource BooleanToVisibilityConverter}}">
        <DataGrid x:Name="SomeDataGrid"
                  IsReadOnly="True"
                  ItemsSource="{Binding Items}"/>
</GroupBox>

问题

在将Page切换到其他页面并且返回时,出现以下绑定异常

System.Windows.Data Error: 4 : 找不到与引用匹配的绑定源

'ElementName=SomeDataGrid'. BindingExpression:Path=HasItems;

我尝试使用x:Reference,但是出现了相同的问题。

请问有人能解释一下我做错了什么吗?

1个回答

2
可能是在某个时刻,Items 集合为空,导致 GroupBox 折叠。当 GroupBox 被折叠时,它会从视图中移除其内容(DataGrid)。
DataGrid 从视图中移除时,Binding 就无法再找到其引用,因此它就会出错。
如果我是你,我会将 GroupBoxVisibility 直接绑定到一个 ViewModel 属性上,而不是将其绑定到 DataGrid 上。
<GroupBox ....
          Visibility="{Binding HasItems,
                               Converter={StaticResource BooleanToVisibilityConverter}}">
        <DataGrid x:Name="SomeDataGrid"
                  IsReadOnly="True"
                  ItemsSource="{Binding Items}"/>
</GroupBox>

在ViewModel中:

public bool HasItems
{
    get
    {
        return Items != null && Items.Count() > 0;
    }
}

public IEnumerable Items
{
    get
    {
        // ...
    }
    set
    {
        // ...
        RaisePropertyChanged("HasItems");
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接