c# - 自定义 WPF 中列表框中选择的可视化

标签 c# wpf templates xaml listbox

我有一个带有如下列表框的控件:

<local:MyControl x:Name="LayoutRoot" ...>

  <local:MyControl.Resources>
    <ItemsPanelTemplate x:Key="myTemplate">
      <StackPanel Background="Yellow"/>
    </ItemsPanelTemplate>
  </local:MyControl.Resources>

  <Border>    
    ...
    <ListBox  ItemsPanel="{DynamicResource myTemplate}">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Rectangle Height="50" Width="200" Margin="10" Fill="Red"/>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>
    ...
  </Border>
</local:MyControl>

这是我运行它时的样子:

enter image description here

列表框根据每个项目的状态在其周围绘制一个“框架”:

  • 未选择:透明
  • 已选择且列表框处于焦点:蓝色
  • 已选择且列表框失去焦点:白色

我猜“框架”是 Rectangle 对象的 Margin 下的 ListBoxItem 背景的可见部分,但我不确定。

我想为每个不同的状态自定义“框架”的外观。您能给我一个如何做到这一点的示例吗?

最佳答案

您看到的不是一个“框架”,而只是您在矩形中设置的边距的结果。 请注意,您不应将矩形设置为 DataTemplate,否则您只会在列表中看到...矩形。只需为此使用一个边框,您可以在其中放置内容(使用 < ContentControl Content={Binding}/>)

要获得正确的颜色,请在 ItemContainerStyle 中使用样式。问题是触发器 在“IsSelected”情况下不起作用,因为默认模板在选择时将背景颜色设置为蓝色,无法更改它。因此,您必须重新定义模板以使 BackGround 不可见,并在该模板内定义触发器。你的风格应该看起来有点像这样:

    <Style x:Key="myStyle" TargetType="ListBoxItem" >
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border Background="{TemplateBinding Background}">
                        <Border Background="Red"  Margin="10">
                            <ContentControl Content="{Binding}" />
                        </Border>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="Black" />
                        </Trigger>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="Red" />
                        </Trigger>
                        <Trigger Property="IsFocused" Value="True">
                            <Setter Property="Background" Value="Orange" />
                        </Trigger>
                    </ControlTemplate.Triggers >
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

现在您可以在 ListBox 中使用此样式: ItemContainerStyle="{StaticResource myStyle}"

请注意,触发器的顺序会更改结果颜色:最后的胜利(例如,对于选定且鼠标悬停的项目)

关于c# - 自定义 WPF 中列表框中选择的可视化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8277843/

相关文章:

c# - 使用 Task.Delay() 的循环是否会造成内存泄漏?

c# - Hmail 服务器 C# SMTP

c# - 如何将自闭标签添加到xml中的元素?

java - java中模板类型的instanceof

ruby-on-rails - Action Mailer 模板的优雅降级/渐进增强?

c# - UpdatePanel、ModalPopupExtender 和输入按键问题

c# - 如何为 List<T> 创建新的通用项?

c# - 将数据绑定(bind)到 DataGridTextColumn.Header 内的 TextBox

c# - 如何获取在 XAML 中定义的 CollectionView

c++ - 在模板中使用 typedef 结构