XAML项目控件:contentpresenter的可见性并不反映每个拥有的项目

时间:2018-10-26 10:09:32

标签: xaml visibility itemscontrol contentpresenter

在ItemsControl中,项目位于ContentPresenter中,因此,如果某个项目的Visibility ='collapsed',则其ContentPresenter仍然具有Visibility ='Visible'... (Here被解释为这种行为)

因此,这两个示例显示的结果不同:

这符合我的预期:

<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>

有人遇到这个问题吗?有解决方法吗?

1 个答案:

答案 0 :(得分:0)

这是预期的行为,因为该按钮不是UniformGrid的直接子代。相反,ItemsControl将以您定义的ContentPresenter为模板的DataTemplate添加到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。