我有带有 View 模型的页面。 Page
使用 Frame.NavigationManager.Navigate()
在 Frame
中显示。
在一个 Page
中,我有一个带有子 DataGrid
的 GroupBox
。我希望 GroupBox
根据 DataGrid
中的项目计数更改它的 Visibility
。
这是我的:
<GroupBox ....
Visibility="{Binding ElementName=SomeDataGrid,
Path=HasItems,
Converter={StaticResource BooleanToVisibilityConverter}}">
<DataGrid x:Name="SomeDataGrid"
IsReadOnly="True"
ItemsSource="{Binding Items}"/>
</GroupBox>
问题
将 Page
更改为另一个并返回后,我有以下绑定(bind)异常
System.Windows.Data Error: 4 : Cannot find source for binding with reference
'ElementName=SomeDataGrid'. BindingExpression:Path=HasItems;
我试过使用 x:Reference
但遇到了同样的问题。
谁能解释一下我做错了什么?
最佳答案
可能 Items
集合在某个时候为空,这使得 GroupBox
变得折叠起来。当 GroupBox
折叠时,它会从 View 中删除其内容(DataGrid
)。
随着 DataGrid
从 View 中移除,Binding
无法再找到它的引用,因此它中断了。
如果我是你,我会将 GroupBox
Visibility
直接绑定(bind)到 ViewModel 属性,而不是将其绑定(bind)到 DataGrid
。
<GroupBox ....
Visibility="{Binding HasItems,
Converter={StaticResource BooleanToVisibilityConverter}}">
<DataGrid x:Name="SomeDataGrid"
IsReadOnly="True"
ItemsSource="{Binding Items}"/>
</GroupBox>
在 View 模型中:
public bool HasItems
{
get
{
return Items != null && Items.Count() > 0;
}
}
public IEnumerable Items
{
get
{
// ...
}
set
{
// ...
RaisePropertyChanged("HasItems");
}
}
关于c# - 绑定(bind)到子项属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32691819/