• 自定义WPF ListBox的选择样式


    (下图:进行多项选择的ListBox)

      首先介绍一种简单地方法:就是通过自定义SystemColors类的参数来自定义WPF ListBox选择颜色的,SystemColors的HighlightBrushKey和HighlightTextBrushKey分别代表ListBoxItem被选中时文字和背景颜色,没有Highlight的BrushKey代表ListBox没有焦点时的选中项文字和背景颜色:

     1 <ListBox>
     2 
     3             <ListBox.Resources>
     4 
     5                 <Style TargetType="ListBoxItem">
     6 
     7                     <Style.Resources>
     8 
     9                         <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Pink"/>
    10 
    11                         <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Gray"/>
    12 
    13                         <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Red"/>
    14 
    15                         <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Green"/>
    16 
    17                     </Style.Resources>
    18 
    19                 </Style>
    20 
    21             </ListBox.Resources>
    22 
    23             <ListBoxItem>AAA</ListBoxItem>
    24 
    25             <ListBoxItem>B</ListBoxItem>
    26 
    27             <ListBoxItem>ccc</ListBoxItem>
    28 
    29         </ListBox>

    这样的话,ListBox选中颜色变成了这样:

      

      可是这种方法仅仅能改变统一的颜色,无法完成其他更多要求。

      那么另一种更强大的方法就是在模板中定义。一种方法就是在控件模板中根据ListBoxItem的IsSelected属性判断是否被选中,然后利用WPF触发器来设置被选中后的样式。但是如果你的ListBox定义了数据模板的话你会发现数据模板是显示在控件模板之上的,因此控件模板上的某些显示元素会被数据模板盖住,如果此类情况发生,那么只能在数据模板上添加选中后的元素设置。这里可以通过一个RelativeBinding = FindAncestor的绑定来寻找可视化树中的ListBoxItem的IsSelected属性来在数据模板中判断ListBoxItem是否被选中。

    本文来自刘圆圆的博客,原文地址:http://www.cnblogs.com/mgen/archive/2011/09/10/2173402.html

  • 相关阅读:
    [Leetcode] Flatten Binary Tree to Linked List
    [Leetcode] Letter Combinations of a Phone Number
    [Leetcode] Distinct Subsequences
    [Leetcode] Partition List
    [Leetcode] Reverse Linked List II
    [Leetcode] Swap Nodes in Pairs
    [Jobdu] 题目1391:顺时针打印矩阵
    [Jobdu] 题目1369:字符串的排列
    [Jobdu] 题目1283:第一个只出现一次的字符
    如何应用ML的建议-下
  • 原文地址:https://www.cnblogs.com/lyghost/p/2750101.html
Copyright © 2020-2023  润新知