WPF DataGridRow background based on id group and converter

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="Background"
        Value="{Binding  Id,Converter={StaticResource idColorConverter}}"/>
    </Style>
</DataGrid.RowStyle>



public class IdColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int index = (int)value;
        return index % 2 == 0 ? Brushes.Red : Brushes.Blue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

 

 

 

 

 

 

 

 

 

 

//xaml
<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:IdColorConverter x:Key="idColorConverter"/>
    </Window.Resources>
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  AutoGenerateColumns="False"
CanUserAddRows="False"
FontSize="50" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.IsContainerVirtualizable="True" VirtualizingPanel.CacheLength="1" VirtualizingPanel.CacheLengthUnit="Item"> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="Background" Value="{Binding Id,Converter={StaticResource idColorConverter}}"/> </Style> </DataGrid.RowStyle> <DataGrid.Columns> <DataGridTextColumn Header="Id" Binding="{Binding Id}"/> <DataGridTextColumn Header="Name" Binding="{Binding Name}"/> <DataGridTextColumn Header="Title" Binding="{Binding Title}"/> <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}"/> </DataGrid.Columns> </DataGrid> </Grid> </Window> //cs using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO.Ports; using System.Runtime.CompilerServices; using System.Text; 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 WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var vm = new MainVM(); this.DataContext=vm; } } public class MainVM : INotifyPropertyChanged { int idx = 0; public MainVM() { InitBooks(); } private void InitBooks() { List<Book> booksList = new List<Book>(); Random rnd = new Random(); for(int i=0;i<10;i++) { int num = rnd.Next(1, 10); List<Book> partList = new List<Book>(); for(int j=0;j< num;j++) { partList.Add(new Book() { Id=i+1, Name=$"Name_{++idx}", Title=$"Title_{idx}", ISBN=$"{Guid.NewGuid().ToString("N")}" }); } booksList.AddRange(partList); } BooksCollection=new ObservableCollection<Book>(booksList); } public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = "") { var handler = PropertyChanged; if (handler!=null) { handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } private ObservableCollection<Book> booksCollection; public ObservableCollection<Book> BooksCollection { get { return booksCollection??new ObservableCollection<Book>(); } set { if (value!=booksCollection) { booksCollection=value; OnPropertyChanged(nameof(BooksCollection)); } } } } public class Book { public int Id { get; set; } public string Name { get; set; } public string Title { get; set; } public string ISBN { get; set; } } public class IdColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { int index = (int)value; return index % 2 == 0 ? Brushes.Red : Brushes.Blue; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }

 

posted @ 2025-07-10 23:16  FredGrit  阅读(9)  评论(0)    收藏  举报