根据最小值更改DataGridRow颜色
问题描述:
我制作了一个包含Button
和DataGrid
的UI。我已在代码的一些计算方法,产生四个列表看起来像这样:根据最小值更改DataGridRow颜色
var L = new List<MyDataObject>();
for (int z = 0; z < list_Exp.Count; z++)
{
var d = new MyDataObject();
d.AmountNeed = Math.Ceiling((goalexp - currentexp)/(list_Exp[z]));
d.TotalLose = d.AmountNeed * (list_Amount_MadeFrom_One[z] * list_BuyPrice_MadeFrom_One[z] + list_Amount_MadeFrom_Two[z] * list_BuyPrice_MadeFrom_Two[z]);
d.TotalGain = d.AmountNeed * list_AmountMade[z] * list_SellPrice[z];
d.TotalCost = d.TotalGain - d.TotalLose;
L.Add(d);
}
一旦我得到的名单,我觉得在一个特定的列表中的最小值:
int i = L.FindIndex(x => x.TotalCost == L.Min(y => y.TotalCost));
,并添加所有名单到dataGrid
:
dataGrid.ItemsSource = L;
现在,我一直在努力的Rows[i]
颜色更改为绿色或任何其他颜色。我曾尝试这样的东西:
grid.Columns["NameOfColumn"].DefaultCellStyle.ForeColor = Color.Gray;
或
dataGrid.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
,并没有什么作品。
谢谢。
答
例如,您可以定义一个RowStyle
和处理Loaded
事件的DataGridRow
容器是这样的:
<DataGrid x:Name="dataGrid">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<EventSetter Event="Loaded" Handler="RowLoaded" />
</Style>
</DataGrid.RowStyle>
</DataGrid>
private void RowLoaded(object sender, RoutedEventArgs e)
{
DataGridRow dgr = sender as DataGridRow;
MyDataObject x = dgr.DataContext as MyDataObject;
if (x.TotalCost == dataGrid.Items.OfType<MyDataObject>().Min(y => y.TotalCost))
dgr.Background = Brushes.Green;
}
only problem is when i scroll down (i have many rows), it colors few rows instead of finding only 1 min and then i get an error: "NullReferenceEXception was unhandled"
您可以在DataGridRow
容器的Background
属性绑定到目前的MyDataObject
以及收集的物品并使用MultiValueConverter
则:
<DataGrid x:Name="dataGrid" xmlns:local="clr-namespace:WpfApplication1">
<DataGrid.Resources>
<local:Converter x:Key="conv" />
</DataGrid.Resources>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource conv}">
<Binding Path="." />
<Binding Path="ItemsSource" RelativeSource="{RelativeSource AncestorType=DataGrid}" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowStyle>
</DataGrid>
namespace WpfApplication1
{
public class Converter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
MyDataObject x = values[0] as MyDataObject;
if(x != null)
{
IEnumerable<MyDataObject> collection = values[1] as IEnumerable<MyDataObject>;
if(collection != null && x.TotalCost == collection.Min(y => y.TotalCost))
return System.Windows.Media.Brushes.Green;
}
return System.Windows.DependencyProperty.UnsetValue;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
你想整行变色?或者只有一个单元格在行中? –
整个行在索引[我]伴侣。 – Ben
dataGridView1是什么类型的控件?您的示例代码似乎显示了您设置用于显示列表的dataGrid的不同控件。 –