首页 > 其他分享 >WPF 自定义ListBox

WPF 自定义ListBox

时间:2023-06-21 16:55:56浏览次数:42  
标签:高亮 JListBox 自定义 ListBoxItem new WPF ListBox typeof

需求:ListBox只在选中时有相应的高亮颜色,光标悬浮或滑动时不显示高亮;以满足在触屏上时不会误导人操作……

 

以下为实现代码:

namespace FrameControlLibrary
{
    /// <summary>
    /// 按照步骤 1a 或 1b 操作,然后执行步骤 2 以在 XAML 文件中使用此自定义控件。
    ///
    /// 步骤 1a) 在当前项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
    /// 元素中:
    ///
    ///     xmlns:MyNamespace="clr-namespace:FrameControlLibrary"
    ///
    ///
    /// 步骤 1b) 在其他项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
    /// 元素中:
    ///
    ///     xmlns:MyNamespace="clr-namespace:FrameControlLibrary;assembly=FrameControlLibrary"
    ///
    /// 您还需要添加一个从 XAML 文件所在的项目到此项目的项目引用,
    /// 并重新生成以避免编译错误:
    ///
    ///     在解决方案资源管理器中右击目标项目,然后依次单击
    ///     “添加引用”->“项目”->[浏览查找并选择此项目]
    ///
    ///
    /// 步骤 2)
    /// 继续操作并在 XAML 文件中使用控件。
    ///
    ///     <MyNamespace:JListBox/>
    ///
    /// </summary>
    public class JListBox : ListBox
    {
        /*        static JListBox()
                {
                    DefaultStyleKeyProperty.OverrideMetadata(typeof(JListBox), new FrameworkPropertyMetadata(typeof(JListBox)));
                }*/
        public JListBox()
        {
            this.Background = Brushes.Transparent;          
            this.Loaded += JListBox_Loaded;
            //this.SelectionChanged += JListBox_SelectionChanged;
        }

        private void JListBox_Loaded(object sender, RoutedEventArgs e)
        {
            this.ItemContainerStyle = new CustomListBoxStyle();
        }

        private void JListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //((ListBoxItem)this.SelectedItem).FocusVisualStyle = (Style)Application.Current.FindResource(SystemParameters.FocusVisualStyleKey);
           // Color color = (Color)ColorConverter.ConvertFromString("#BEE6FD");
            //((ListBoxItem)this.SelectedItem).Background = SystemColors.HighlightBrush;//new SolidColorBrush(color);
        }
    }

    public class CustomListBoxStyle : Style
    {
        public CustomListBoxStyle()
        {
            TargetType = typeof(ListBoxItem);

            Setter templateSetter = new Setter()
            {
                Property = ListBoxItem.TemplateProperty
            };

            ControlTemplate template = new ControlTemplate(typeof(ListBoxItem));
            FrameworkElementFactory borderFactory = new FrameworkElementFactory(typeof(Border));
            borderFactory.SetValue(Border.BackgroundProperty, new TemplateBindingExtension(ListBoxItem.BackgroundProperty));
            borderFactory.SetValue(Border.BorderThicknessProperty, new Thickness(1));

            FrameworkElementFactory contentPresenterFactory = new FrameworkElementFactory(typeof(ContentPresenter));
            contentPresenterFactory.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            contentPresenterFactory.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);

            borderFactory.AppendChild(contentPresenterFactory);
            template.VisualTree = borderFactory;

            templateSetter.Value = template;
            Setters.Add(templateSetter);

            //选中颜色
            Setter backgroundSetter = new Setter();
            backgroundSetter.Property = ListBoxItem.BackgroundProperty;
            backgroundSetter.Value = Brushes.Transparent;

            DataTrigger selectedTrigger = new DataTrigger();
            selectedTrigger.Binding = new Binding("IsSelected") { RelativeSource = new RelativeSource(RelativeSourceMode.Self) };
            selectedTrigger.Value = true;
            selectedTrigger.Setters.Add(new Setter(ListBoxItem.BackgroundProperty, new SolidColorBrush(Color.FromArgb(0xFF, 0xBE, 0xE6, 0xFD))));

            Triggers.Add(selectedTrigger);
            Setters.Add(backgroundSetter);

        }
    }


}

注:开始时实现选中item背景色改变是利用的SelectionChanged事件来改变,但是改变后会造成这个item的背景总是高亮,即取消选中后它还是高亮。于是后续将xaml中实现选中高亮的代码改为了后台代码,以实现这一目的。后续有更好办法,再次改进……

 

以下为在page或window中实现listbox仅选中item高亮的代码:

        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListBoxItem}">
                        <Border Background="{TemplateBinding Background}"
                                BorderThickness="1">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <!--<Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightColor}}"/>
                </Trigger>-->
                <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource Self}}" Value="true">
                    <Setter Property="Background" Value="#BEE6FD"/>
                </DataTrigger>

            </Style.Triggers>
        </Style>

 

标签:高亮,JListBox,自定义,ListBoxItem,new,WPF,ListBox,typeof
From: https://www.cnblogs.com/chengcanghai/p/17496667.html

相关文章

  • WPF编译时“所使用的 PresentationFramework 6.0.2 高于所引用的标识为 6.0.0 程序集
    一个用.NET6开发的WPF应用,前面编译执行都正常。同事要出差,把代码拷贝到开发本上编译时,编译报错。编译报错的内容主要如标题所示:所使用的PresentationFramework6.0.2高于所引用的标识为PresentationFramework6.0.0程序集PresentationFramework上网搜索了一下,搜到了林......
  • 自定义Feign配置
    配置Feign日志有两种方式:配置文件方式和Java代码方式全局生效:(1)方式一:配置文件方式feign:client:config:default:#这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置loggerLevel:FULL#日志级别(2)方式二:Java代码方式需......
  • Flutter — 文本为什么可以被编辑?如何自定义编辑的行为?
    通过阅读本文,您将了解到知道在Flutter中关于文本的整体逻辑;可编辑文本包含哪些内容;如何自定义可编辑行为;如何优雅的实现文本表单。前言:在上一篇文章中,我们讲解了Flutter文本的组成部分和Flutter文本渲染到屏幕上的逻辑。文本的输出我们已经分析完成了,那么文本的输入又是怎么样的......
  • 直播开发app,css 自定义滚动条样式
    直播开发app,css自定义滚动条样式<divclass="content-wrap">  <div>    内容XXXX  </div> </div>  <style> //content-wrap样式.content-wrap{  flex:1;  overflow-y:scroll;  box-sizing:border-box;  padding:010px;  ......
  • WPF 自定义ComboBox
    需求:ComboBox下拉列表,在光标移出ComboBox后,下拉列表立即收起。 利用WPF的 自定义控件继承于ComboBox开发项目中需要的JComboBox,其代码如下:namespaceFrameWPF{///<summary>///按照步骤1a或1b操作,然后执行步骤2以在XAML文件中使用此自定义控件。......
  • 【Java】使用 validation 完成自定义校验注解
    总括:validation让我们简化了开发过程,可以使用简单的一个注解就实现了很多常见的检验数据的功能,同时支持自定义注解。spring-boot-starter-validation是由SpringBoot整合的一套用于处理 validation的约定化自动配置启动器。Spring系列框架通过简单的安装依赖即可直接使用......
  • 前端Vue自定义列表表格信息展示可用于商品规格参数展示
    前端Vue自定义列表表格信息展示可用于商品规格参数展示 ,下载完整代码请访问uni-app插件市场地址:https://ext.dcloud.net.cn/plugin?id=13131效果图如下:使用方法<!--table-list:表格数组数组里对象可自定义字段 --><cc-defineTable:table-list="tableArr"></cc-defin......
  • 前端Vue自定义顶部搜索框 热门搜索 历史搜索 用于搜索跳转使用
    前端Vue自定义顶部搜索框热门搜索历史搜索用于搜索跳转使用,下载完整代码请访问uni-app插件市场地址:https://ext.dcloud.net.cn/plugin?id=13128效果图如下:自定义顶部搜索框用于搜索跳转使用方法<!--自定义顶部搜索框用于搜索跳转skipUrl:跳转url为绝对路径/pages开......
  • 多路Qt串口通信源码C++语言接口自定义协议帧Qt读写配置文件ini出售: 可变长定长通信接
    多路Qt串口通信源码C++语言接口自定义协议帧Qt读写配置文件ini出售:可变长定长通信接口协议实现Qt多路串口发送接收SerialProtocol.rar工控自定义报文可用于嵌入式,单片机,ARM,DSP等常见的串口通信中,出售在应用实践中编写总结的源代码,实现自定义的串口通信协议,包括报文头部、长度......
  • 自定义可编辑的对话框
    Dialogdialog=newDialog(this);dialog.setContentView(R.layout.your_dialog_file);ButtonyourButton=dialog.findViewById(R.id.yourButton);finalEditTexttext=dialog.findViewById(R.id.yourTextEdit);yourButton.setOnClickListener({publicvo......