如何使用属性绑定(bind)更改 GridViewItems
可见性?
我无法创建另一个 ObservableCollection
来过滤我用作 ItemsSource
的那个。我尝试使用 GridView.ItemContainerStyle
来更改 GridViewItem
样式,但它似乎不适用于绑定(bind)(尽管如果我将值设置为 Collapsed 它会起作用)。
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="Visibility" Value="{Binding IsVisible, Converter={StaticResource booleanToVisibilityConverter}}" />
</Style>
</GridView.ItemContainerStyle>
我还尝试使用 DataTemplateSelector
。我可以使用绑定(bind)隐藏项目,但是我的 GridView
上有间隙,因为 ItemContainer
仍然存在并且不会折叠。
我需要 GridView
项折叠而不仅仅是隐藏。
编辑:为什么我要摆脱过滤的ObservableCollections
?
我正在尝试镜像 2 个 GridViews
和 1 个 ListView
与相同的 ItemsSource
和 SelectedItem
都绑定(bind)我的 ViewModel 属性 Items
和 Current
。
没有过滤器,它可以像我预期的那样工作,没有 SelectionChanged 事件,但有只有双向绑定(bind)。
但是那些 GridView/Listview
必须有一些差异,例如可供选择的项目及其 DataTemplates
。所以我正在使用给我带来问题的过滤集合。
例如:
GridView1
有项目 1、2 和 3GridView2
只有项目 1 和 3- 我选择
GridView1
的第 1 项 - 我选择
GridView1
的项目 2
当我选择项目 1 时,它也会在 GridView2
上被选中。现在好了。当我选择项目 2 时,项目 1 在 GridView2
上保持选中状态。 GridView2
现在应该没有选择,但如果我强制选择它,它将始终取消选择 GridView2
的项目 2,因为两者的 SelectedItem
都是双向绑定(bind)的.
我希望这是可以理解的,因为英语不是我的母语。
最佳答案
所以首先,样式不起作用,因为 WinRT 显然不支持 setter 中的绑定(bind)(请参阅 here)。本文确实提到了解决此问题的方法,希望它对您有用(尽管我自己还没有尝试过)。
如果不成功,GridView 最终只是一个 ItemsControl,因此您应该能够通过将其 ItemsPanel 属性设置为自定义面板来手动覆盖布局。您可以制作一个像这样的小型自定义面板,以与用于折叠 GridViewItems 内容的 DataTemplateSelector 结合使用:
class CustomPanel : Panel
{
//Children of this panel should be of type GridViewItem (which is the ItemContainer for the
//ItemsControl)
protected override Size MeasureOverride(Size availableSize)
{
foreach (var child in this.Children)
{
var interior = (UIElement)VisualTreeHelper.GetChild(child, 0);
interior.Measure(availableSize);
if (interior.DesiredSize.Width == 0 && interior.DesiredSize.Height == 0)
//Skip this item
else
{
child.Measure(availableSize);
//Update the total measure of the panel with child.DesiredSize...
}
//Return the total calculated size
}
}
protected Size override ArrangeOverride(Size finalSize)
{
foreach (var child in this.Children)
{
var interior = (UIElement)VisualTreeHelper.GetVisualChild(child, 0);
if (interior.DesiredSize.Width == 0 || interior.DesiredSize.Height == 0)
//Skip this item
else
//Call child.Arrange with the appropriate arguments and update the total size
//used...
//Return the total size used
}
}
}
这段代码可以稍微清理一下,但像这样的东西应该能够解决处理出现的空 GridViewItems 的问题。
关于c# - 使用绑定(bind)更改 GridView 项的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16443734/