[英]How can I change the background color of a gridview cell, based on a conditional statement?
[英]How can I change a datagrid cell color based on conditional comparing cell values?
我對 WPF 和 C# 還很陌生,所以如果這是一個新手問題,請原諒我。 我有一個數據網格,其中填充了數據表中的值。 對於數據網格中的每一行,如果特定單元格的值大於另一個單元格的值,我想突出顯示該單元格。 例如:
| "A" | "B" |
| 5 | 4 | <- A[0] would be highlighted yellow
| 3 | 3 | <- A[1] would not be highlighted yellow
我查看了創建一個如果 A>B 為 True 的 bool 列,然后嘗試將觸發器映射到 XAML 代碼中的該列,但我無法弄清楚如何將 setter 屬性分配給不同於綁定。 我最近也嘗試了以下方法:
foreach (DataRowView row in dgTrending.Items)
{
if ((int)row.Row["A"] > (int)row.Row["B"])
{
DataGridCell color =
(DataGridCell)dgTrending.ItemContainerGenerator.ContainerFromItem(row.Row["A"]);
color.Background = new SolidColorBrush(Colors.Yellow);
}
}
對於上面的代碼,變量 color 被設置為 null,所以我顯然在那里做錯了什么。 我知道遍歷每一行效率低下,但我很難找到更好的方法。 理想情況下,我可以通過后面的代碼來做到這一點,因為我無法向 XAML 添加條件(至少不是我見過的)。 任何幫助將不勝感激。 謝謝!
mvvm wpf datagrid 更改單元格內容顏色
郵政編碼
<UserControl x:Class="RetailSoft.Stock_Reports.FrmCurrentItemWiseStock"
.....
xmlns:Converter="clr-namespace:RetailSoft.Converter"
>
<UserControl.Resources>
<Converter:PositiveNegativeConverter x:Key="PositiveNegativeConverter"/>
</UserControl.Resources>
數據網格列
<DataGridTextColumn
Header="Stock"
MinWidth="70" MaxWidth="1000"
x:Name="ProductName"
Binding="{Binding Stock}"
CellStyle="{StaticResource customCellStyle}"
>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextBlock.Foreground" Value="{Binding Stock,Converter={StaticResource PositiveNegativeConverter}}"/>
</Style>
</DataGridTextColumn.ElementStyle>
<DataGridTextColumn.HeaderStyle>
<Style
TargetType="DataGridColumnHeader">
<Setter
Property="Background"
Value="SteelBlue"
/>
<Setter
Property="HorizontalContentAlignment"
Value="Center"
/>
<Setter
Property="Foreground"
Value="White"
/>
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
和轉換類代碼
public class PositiveNegativeConverter : IValueConverter
{
public object Convert(object Stock, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (Stock==null)
{
Stock = "";
}
string Stocks = Stock.ToString();
bool revert = (Stocks as string).StartsWith("-");
string stringValue = Stock as string;
string compareValue = parameter as string;
if (revert)
{
return Brushes.Tomato;
}
else
return Brushes.LimeGreen;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.