XAML 项控件:内容演示者可见性不反映每个拥有的项目



In ItemsControl项在ContentPresenter中,因此如果项的Visibility="已折叠",则其ContentPresenter的Visibility仍然="可见"。。。(这里解释了这种行为(

所以这两个例子并没有显示出相同的结果:

正如我所期望的那样:

<UniformGrid Columns="1">
<Button Content="0"/>
<Button Content="1"/>
<Button Content="2" Visibility="Collapsed"/>
<Button Content="3"/>
</UniformGrid>

这并不像我预期的那样起作用(如果第三个按钮被折叠,UniformGrid也会为其保留空间(:

<ItemsControl>
<ItemsControl.ItemsSource>
<x:Array Type="{x:Type System:Int32}">
<System:Int32>0</System:Int32>
<System:Int32>1</System:Int32>
<System:Int32>2</System:Int32>
<System:Int32>3</System:Int32>
</x:Array>
</ItemsControl.ItemsSource>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="1"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Visibility="{Binding ., Converter={StaticResource CalculatorConverter}, ConverterParameter=IIF({0}=2,'Collapsed','Visible')}" Content="{Binding .}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

有人有这个问题吗?有变通办法吗?

这是预期行为,因为按钮不是UniformGrid的直接子级。相反,ItemsControl将使用您定义的DataTemplate模板化的ContentPresenter添加到UniformGrid中。因此,基本上视觉树类似于:1

<UniformGrid>
....
<ContentPresenter>
<Button Visibility="Collapsed" />
</ContentPresenter>
....
</UniformGrid>

我认为这清楚地说明了为什么即使按钮被折叠,网格中的空间也会被保留。当然,为了弥补这一点,您应该折叠ContentPresenter。它可以通过使用ItemsControl.ItemContainerStyle属性来实现:

<ItemsControl>
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type ContentPresenter}">
<Setter Property="Visiblity" Value="{Binding ., Converter=...}" />
</Style>
</ItemsControl.ItemContainerStyle>
...
</ItemsControl>

1提供的代码只是可视化树的说明,不是有效的WPF XAML

相关内容

最新更新