WPF列表样式

这篇具有很好参考价值的文章主要介绍了WPF列表样式。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

WPF的数据绑定系统自动生成列表项对象,为单个项应用所需的样式不是很容易。解决方案是ItemContainerStyle 属性。如果设置了ItemContainerStyle 属性,当创建列表项时,列表控件会将其向下传递给每个项。对于ListBox控件,每个项有ListBoxItem 对象表示,对于CombBox 控件,则对应是 CombBoxItem。

交替条目样式

WPF通过两个属性为交替项提供内置支持:AlternationCount 和 AlternationIndex。

<Window>
    <Window.Resources>
        <Style x:Key="listBoxItemStyle" TargetType="{x:Type ListBoxItem}">
            <Setter Property="Background" Value="LightBlue"/>
            <Setter Property="Margin" Value="5"></Setter>
            <Setter Property="Padding" Value="5"></Setter>
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="LightBlue"/>
                </Trigger>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="DarkRed"/>
                    <Setter Property="Foreground" Value="White"/>
                    <Setter Property="BorderBrush" Value="Black"/>
                    <Setter Property="BorderThickness" Value="10"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid x:Name="myGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition MinHeight="100"/>
        </Grid.RowDefinitions>
        <ListBox Grid.Row="0" Grid.Column="0" ItemContainerStyle="{StaticResource listBoxItemStyle}" ItemsSource="{Binding Path=Orders}" AlternationCount="2" DisplayMemberPath="Price"/>
    </Grid>
</Window>

也可以直接将样式设置到ListBox层次

<Window>
    <Window.Resources>
        <Style x:Key="checkBoxListStyle" TargetType="{x:Type ListBox}">
            <Setter Property="SelectionMode" Value="Multiple"></Setter>
            <Setter Property="ItemContainerStyle">
                <Setter.Value>
                    <Style TargetType="{x:Type ListBoxItem}">
                        <Setter Property="Margin" Value="2"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                                    <CheckBox IsChecked="{Binding Path=IsSelected,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay}">
                                        <ContentPresenter/>
                                    </CheckBox>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid x:Name="myGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition MinHeight="100"/>
        </Grid.RowDefinitions>
        <ListView Grid.Row="1" Grid.Column="0" Style="{StaticResource checkBoxListStyle}" ItemsSource="{Binding Path=Orders}" DisplayMemberPath="Price" Name="checkButtonListBox"/>
    </Grid>
</Window>

样式选择器

可以使用样式选择器来为不同的子项提供不同的样式,自定义样式选择器需要继承自 StyleSelector 类,需要重写 SelectStyle() 方法。

public class SingleCriteriaHighlightStyleSelector : StyleSelector
{
    public Style DefaultStyle { get; set; }
    public Style HighlightStyle { get; set; }
    public string PropertyToEvaluate { get; set; }
    public string PropertyValueToHighlight { get; set; }
    public override Style SelectStyle(object item, DependencyObject container)
    {
        Order order = (Order)item;
        if (order.Price > 1000)
        {
            return HighlightStyle;
        }
        else
        {
            return DefaultStyle;
        }
    }
}

完整的代码文件:

MainWindow.xaml

<Window x:Class="ListBoxStyle.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ListBoxStyle"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style x:Key="listBoxItemStyle" TargetType="{x:Type ListBoxItem}">
            <Setter Property="Background" Value="Blue"/>
            <Setter Property="Margin" Value="5"></Setter>
            <Setter Property="Padding" Value="5"></Setter>
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="LightBlue"/>
                </Trigger>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="DarkRed"/>
                    <Setter Property="Foreground" Value="White"/>
                    <Setter Property="BorderBrush" Value="Black"/>
                    <Setter Property="BorderThickness" Value="10"/>
                </Trigger>
            </Style.Triggers>
        </Style>
        <Style x:Key="radioButtonListStyle" TargetType="{x:Type ListBoxItem}">
            <Setter Property="Background" Value="Blue"/>
            <Setter Property="Margin" Value="5"></Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListBoxItem}">
                        <RadioButton Focusable="False" IsChecked="{Binding Path=IsSelected,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay}">
                            <ContentPresenter/>
                        </RadioButton>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="checkBoxListStyle" TargetType="{x:Type ListBox}">
            <Setter Property="SelectionMode" Value="Multiple"></Setter>
            <Setter Property="ItemContainerStyle">
                <Setter.Value>
                    <Style TargetType="{x:Type ListBoxItem}">
                        <Setter Property="Margin" Value="2"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                                    <CheckBox IsChecked="{Binding Path=IsSelected,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay}">
                                        <ContentPresenter/>
                                    </CheckBox>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="DefaultStyle" TargetType="{x:Type ListBoxItem}">
            <Setter Property="Background" Value="LightYellow" />
            <Setter Property="Padding" Value="2" />
        </Style>
        <Style x:Key="HighlightStyle" TargetType="{x:Type ListBoxItem}">
            <Setter Property="Background" Value="LightSteelBlue" />
            <Setter Property="FontWeight" Value="Bold" />
            <Setter Property="Padding" Value="2" />
        </Style>
    </Window.Resources>
    <Grid x:Name="myGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition MinHeight="100"/>
        </Grid.RowDefinitions>
        <ListBox Grid.Row="0" Grid.Column="0" ItemContainerStyle="{StaticResource listBoxItemStyle}" ItemsSource="{Binding Path=Orders}" AlternationCount="3" DisplayMemberPath="Price"/>
        <ListBox Grid.Row="0" Grid.Column="1" ItemContainerStyle="{StaticResource radioButtonListStyle}" ItemsSource="{Binding Path=Orders}" DisplayMemberPath="Price" Name="radioButtonListBox"/>
        
        <ListView Grid.Row="1" Grid.Column="0" Style="{StaticResource checkBoxListStyle}" ItemsSource="{Binding Path=Orders}" DisplayMemberPath="Price" Name="checkButtonListBox"/>
        <ListBox Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Path=Orders}" DisplayMemberPath="Price" Name="styleSelectorListBox">
            <ListBox.ItemContainerStyleSelector>
                <local:SingleCriteriaHighlightStyleSelector DefaultStyle="{StaticResource DefaultStyle}" HighlightStyle="{StaticResource HighlightStyle}"></local:SingleCriteriaHighlightStyleSelector>
            </ListBox.ItemContainerStyleSelector>
        </ListBox>
        
        <Button Grid.Row="4" Click="Button_Click">Test</Button>
        <Button Grid.Row="4" Grid.Column="1" Click="Button_Click_1">Test</Button>
    </Grid>
</Window>

MainWindow.xaml.cs文章来源地址https://www.toymoban.com/news/detail-685559.html

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ListBoxStyle;

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    protected virtual bool SetProperty<T>(ref T member, T value, [CallerMemberName] string? propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(member, value))
        {
            return false;
        }
        member = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}
public class Order : ViewModelBase
{
    public decimal price = 0;
    public decimal Price { get => price; set => SetProperty(ref price, value); }
    public int volume = 0;
    public int Volume { get => volume; set => SetProperty(ref volume, value); }

    public DateTime orderDate = DateTime.Now;
    public DateTime OrderDate { get => orderDate; set => SetProperty(ref orderDate, value); }

    public string image = string.Empty;
    public string Image { get => image; set => SetProperty(ref image, value); }
}

public class SingleCriteriaHighlightStyleSelector : StyleSelector
{
    public Style DefaultStyle { get; set; }
    public Style HighlightStyle { get; set; }
    public string PropertyToEvaluate { get; set; }
    public string PropertyValueToHighlight { get; set; }
    public override Style SelectStyle(object item, DependencyObject container)
    {
        Order order = (Order)item;
        if (order.Price > 1000)
        {
            return HighlightStyle;
        }
        else
        {
            return DefaultStyle;
        }
    }
}



public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        myGrid.DataContext = this;

        Order order1 = new Order();
        Order order2 = new Order();
        Order order3 = new Order();
        Order order4 = new Order();

        order1.Price = 100;
        order1.Volume = 10;

        order2.Price = 1000;
        order2.Volume = 100;

        order3.Price = 10000;
        order3.Volume = 1000;

        order4.Price = 100000;
        order4.Volume = 10000;

        Orders.Add(order1);
        Orders.Add(order2);
        Orders.Add(order3);
        Orders.Add(order4);
    }

    public ObservableCollection<Order> Orders {get; set;} = new ();

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        string message = "";
        if(radioButtonListBox.SelectedItem != null)
        {
            Order order = (Order)radioButtonListBox.SelectedItem;
            message = order.Price.ToString();
        }
        message += "\n";
        foreach (var selectedItem in checkButtonListBox.SelectedItems)
        {
            Order order = (Order)selectedItem;
            message += order.Price.ToString() + " ";
        }
        MessageBox.Show(message);
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        Orders[1].Price = 50000;
        StyleSelector selector = styleSelectorListBox.ItemContainerStyleSelector;
        styleSelectorListBox.ItemContainerStyleSelector = null;
        styleSelectorListBox.ItemContainerStyleSelector = selector;

    }
}

到了这里,关于WPF列表样式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 雷军:我的程序人生路

    今天有朋友发给我一篇我在20年前在BBS上写的帖子。那还是1996年,我们通过电话线拨号连接到西点BBS上飙帖子玩的年代。那是一个互联网混沌初开的年代,那是一个BBS和Email几乎主宰了全部互联网的年代,那是一个青春的理想和热血沸腾的年代。 我是一个程序员,一个软件工

    2024年02月04日
    浏览(47)
  • 哈工大CSAPP程序人生大作业

    正在上传…重新上传取消 计算机系统 大作业 题     目   程序人生 -Hello’s P2P  专       业    计算机科学与技术        学    号   2021110991             班    级      2103101             学       生         安心           指 导 教 师    

    2023年04月24日
    浏览(54)
  • C罗老矣,我的程序人生还有多远

    ☆ 随着12月11号摩洛哥1-0葡萄牙比赛的结束,不仅说明葡萄牙对要结束本届卡塔尔世界杯了,就连C罗此生的世界杯之旅也将画上句号了。 ☆ 37岁的球星本该是人生最璀璨的阶段,但在足球生涯中,这已经是大龄了。不禁让我想到,身为开发的我,也大概类似吧。   目录  1、

    2024年01月16日
    浏览(37)
  • 程序人生——Java数组和集合使用建议(2)

    程序人生——Java数组和集合使用建议(2) 需求:要删除一个ArrayList中的20-30范围内的元素;将原列表转换为一个可变列表,然后使用subList获取到原列表20到30范围内的一个视图(View),然后清空该视图内的元素,即可在原列表中删除20到30范围内的元素 建议72:生成子列表后

    2024年03月19日
    浏览(34)
  • 【程序人生】上海城市开发者社区小聚有感

    📫作者简介: 小明java问道之路 , 2022年度博客之星全国TOP3 ,专注于后端、中间件、计算机底层、架构设计演进与稳定性建设优化,文章内容兼具广度、深度、大厂技术方案,对待技术喜欢推理加验证,就职于知名金融公司后端高级工程师。          📫 热衷分享,喜欢原

    2024年02月06日
    浏览(54)
  • 【程序人生】如何在工作中保持稳定的情绪?

    在工作中保持稳定的情绪是现代生活中一个备受关注的话题。随着职场压力和工作挑战的增加,我们常常发现自己情绪波动不定,甚至受到负面情绪的困扰。然而,保持稳定的情绪对于我们的工作效率、人际关系和整体幸福感都至关重要。 无论你是一位职场新人还是一位资深

    2024年02月15日
    浏览(33)
  • 程序人生 | 编程的上帝视角应该怎么去找

      前言 📫 作者简介 :小明java问道之路,专注于Linux内核/汇编/HotSpot/C++/Java/源码/架构/算法 就职于大型金融公司后端高级工程师,擅长交易领域的高安全/可用/并发/性能的架构设计📫  🏆 CSDN专家博主/Java优质创作者/CSDN内容合伙人 、InfoQ签约作者 、阿里云专家/签约博主、

    2023年04月24日
    浏览(72)
  • 【程序人生】还记得当初自己为什么选择计算机?

            还记得人生中第一次接触计算机编程是在高中,第一门编程语言是Python(很可惜由于条件限制的原因,当时没能坚持学下去......现在想来有点后悔,没能坚持,唉......)。但是,错过的就错过了,把握当前才是正确的选择。努力最好的时机永远是在过去,其次就在当

    2024年02月04日
    浏览(46)
  • 《人生苦短,我学Python》——第一个python程序

    Hello!朋友们大家好,从今天开始,我们将学习 Python 的相关内容。 首先,让我们来思考一个问题,编程是什么? 编程是人类与电脑沟通的过程,可以告诉电脑做什么以及怎么做。人类用编程构建数字世界,比如网站、App、办公软件等等。 世界上有很多种编程语言,比如C,

    2024年02月11日
    浏览(36)
  • 人工智能AI时代:全栈程序员的人生规划

    博主 默语带您 Go to New World. ✍ 个人主页—— 默语 的博客👦🏻 《java 面试题大全》 🍩惟余辈才疏学浅,临摹之作或有不妥之处,还请读者海涵指正。☕🍭 《MYSQL从入门到精通》数据库是开发者必会基础之一~ 🪁 吾期望此文有资助于尔,即使粗浅难及深广,亦备添少许微薄

    2024年02月11日
    浏览(68)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包