【问题标题】:Change ListBox item style at run-time在运行时更改 ListBox 项样式
【发布时间】:2009-10-09 14:18:57
【问题描述】:

我有一个列表框,其中的项目使用 ResourceDictionary 样式设置样式,然后附加到 ItemContainerStyle 属性。这使我的 ListBoxItems 的 BorderThickness 假设为 1。

现在我想单独折叠项目,所以我使用 Visibility.Collapsed 但由于某种原因,ItemContainerStyle 创建的边框不会与列表框项目的其余部分一起消失。就好像它在我的项目后面创建了一个层,尽管项目被折叠,但它仍然存在。

如何在运行时将 ListBoxItem(或这个额外层)的 BorderThickness 设置为 0?

问候 sk

【问题讨论】:

  • 你的项目真的崩溃了吗?即项目的总高度是否正确改变?如果没有,边界厚度将不是唯一需要解决的问题。
  • 项目确实折叠了。但边界仍然存在:(
  • 听起来你正在折叠代表你的项目的 UI 对象,而不是容器。容器是一个层,其中包含您的 UI 对象,并在您的项目被选中、悬停等时添加额外的样式......容器对 ListViewItem 类型进行操作。而 UI 元素由 DataTemplate 定义并分配给 ListBox.ItemTemplate 属性。它对源集合中的项目类型进行操作。尝试在 ItemTemplate 而不是 ItemContainerStyle 中定义边框。

标签: c# wpf listbox listboxitem


【解决方案1】:

尝试使用自定义触发器:

    <Style TargetType="{x:Type ListBoxItem}">
        <Style.Triggers>
            <Trigger Property="Visibility" Value="Collapsed">
                <Setter Property="BorderThickness" Value="0,0,0,0"/>
            </Trigger>
            <Trigger Property="Visibility" Value="Visible">
                <Setter Property="BorderThickness" Value="0,0,0,1"/>
            </Trigger>
        </Style.Triggers>
    </Style>

显然改变你的边框厚度值,但这应该可以解决问题(或非常接近这个)

【讨论】:

    【解决方案2】:

    我试图重现该问题,但发现边框确实按预期折叠:

    <StackPanel>
      <StackPanel.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibility" />
        <Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem">
          <Setter Property="BorderBrush" Value="Black" />
          <Setter Property="BorderThickness" Value="1" />
        </Style>
      </StackPanel.Resources>
    
      <CheckBox x:Name="_show"
                Content="Show Item 2"
                IsChecked="True" />
    
      <ListBox ItemContainerStyle="{StaticResource ListBoxItemStyle}">
        <ListBoxItem Content="Item 1" />
        <ListBoxItem Content="Item 2">
          <ListBoxItem.Visibility>
            <Binding ElementName="_show"
                     Path="IsChecked"
                     Converter="{StaticResource BooleanToVisibility}" />
          </ListBoxItem.Visibility>
        </ListBoxItem>
        <ListBoxItem Content="Item 3" />
      </ListBox>
    </StackPanel>
    

    您确定 ListBoxItem 是被折叠的对象(相对于 ListBoxItem 中的 UI 对象)?

    【讨论】:

      【解决方案3】:
      foreach(ListBoxItem item in listBox1.Items){
         item.BorderThickness = new Thickness(0);
      }
      

      这是答案,但我不建议这样做,因为您无法撤消样式以恢复原始样式,而是应该根据某些状态选择一些不同的数据绑定方法。

      【讨论】:

      • 我已经尝试过了,但它不适用。反映 BorderThickness 值显示 {BorderThickness 0,0,0,0},虽然它应该是 {BorderThickness 0,0,0,1}
      • 这完全行不通。它将返回 datamodel 而不是 listboxitem
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      相关资源
      最近更新 更多