C# WPF DataGrid 根据某列的值设置行的背景色

最简单的方法是 使用 datagrid的LoadingRow事件。
     private void datagrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            var drv = e.Row.Item as DataRowView;
            switch (drv["ID"].ToString())
            {
                case "1": e.Row.Background = new SolidColorBrush(Colors.Green);
                    break;
                case "2": e.Row.Background = new SolidColorBrush(Colors.Yellow);
                    break;
                case "3": e.Row.Background = new SolidColorBrush(Colors.CadetBlue);
                    break;


            }   
        }


                
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C# WPF中,使用MVVM模式来实现DataGrid自动添加序号是比较常见的需求。下面是一种实现方式: 1. 首先,在ViewModel中定义一个ObservableCollection来存储数据源,并在构造函数中初始化该集合。 2. 在XAML中,使用DataGrid控件绑定到ViewModel中的数据源集合,并设置AutoGenerateColumns为False。 3. 在DataGrid的列定义中,添加一个新的列,用于显示序号。可以使用DataGridTextColumn,并设置Binding为"{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=Items.IndexOf(.)+1}"。 4. 这样,当数据源集合发生变化时,DataGrid会自动更新序号。 下面是一个示例代码: ViewModel.cs: ```csharp public class ViewModel : INotifyPropertyChanged { private ObservableCollection<Item> items; public ObservableCollection<Item> Items { get { return items; } set { items = value; OnPropertyChanged(nameof(Items)); } } public ViewModel() { Items = new ObservableCollection<Item>(); // 初始化数据源集合 } // INotifyPropertyChanged接口实现代码省略... } ``` MainWindow.xaml: ```xaml <Window x:Class="WpfApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApp" Title="MainWindow" Height="450" Width="800"> <Grid> <DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="#" Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=Items.IndexOf(.)+1}" /> <!-- 其他列定义 --> </DataGrid.Columns> </DataGrid> </Grid> </Window> ``` 在这个示例中,ViewModel类中的Items属性是用来存储数据源的ObservableCollection。在MainWindow.xaml中,使用DataGrid控件绑定到Items属性,并添加一个新的列来显示序号。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值