[英]How to change the background color of a certain row in a DataGrid
例如,在 xaml 中,我有一個名為 PersonList 的 DataGrid:
<DataGrid Name="PersonList" />
在代碼隱藏中,我有一個 Person 集合:
ObservableCollection<Person> persons = ViewModel.PersonModel;
然后我創建了一個 Person DataTable,並通過以下方式將其綁定到 PersonList:
PersonDataTable.Columns.Add("Name", typeof(string));
PersonDataTable.Columns.Add("Age", typeof(int));
foreach (var person in persons)
{
if (person != null)
{
PersonDataTable.Rows.Add(
Person.Name,
Person.Age
);
}
}
PersonList.ItemSource = PersonDataTable.AsDataView;
我的問題是,如何更改某一行的背景顏色? 例如,更改人員年齡> 50 行的背景顏色
我試圖通過訪問 PersonList.ItemSource 中的每一行來做到這一點,但我失敗了,該行始終為空:
int count = 0;
foreach (var person in PersonList.ItemSource)
{
var row = PersonList.ItemContainerGenerator.ContainerFromItem(person) as DataGridRow;
if (PersonDataTable.Rows[count].Field<int>(1) > 50)
{
row.Background = Brushes.Gray;
}
count++;
}
請幫助,WPF大師:)
使用轉換器嘗試您的邏輯,如下所示:
這是我的 AgeAboveLimitConverter 文件:
using System;
using System.Windows.Data;
namespace DataGridSample.Converter
{
public class AgeAboveLimitConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
return (int)value > 50;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
}
然后在您的 datagrid xaml 文件中,添加命名空間xmlns:converter="clr-namespace:DataGridSample.Converter"
在 DataGrid 中為 DataGridRow 添加樣式,
<Grid>
<Grid.Resources>
<converter:AgeAboveLimitConverter x:Key="AgeConverter"/>
</Grid.Resources>
<DataGrid Name="PersonList">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow" >
<Setter Property="Background" Value="Transparent" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Age,Converter={StaticResource AgeConverter}}" Value="true">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
</Grid>
你快到了。 請嘗試以下操作:
int count = 0;
foreach (var person in PersonList.ItemSource)
{
var row = PersonList.ItemContainerGenerator.ContainerFromItem(person) as DataGridRow;
if (PersonDataTable.Rows[count].Field<int>(1) > 50)
{
row.DefaultCellStyle.BackColor = Color.Gray;
}
count++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.