/ / Color DataGridCell według Cellvalue - c #, wpf, binding, datagrid, datagridcell

Color DataGridCell by Cellvalue - c #, wpf, binding, datagrid, datagridcell

i "ve WPF DataGrid z inną liczbą kolumn. Chcę kolor pojedynczych komórek zależnych od wartości. Na przykład: Jeśli wartość komórki wynosi 0, to czerwony.

To są moje eksperymenty:

<DataGrid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" x:Name="DataGrid"  SelectionUnit="Cell">
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<!--experiment 1 -->
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Value, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" Value="0">
<Setter Property="Background" Value="LimeGreen"/>
</DataTrigger>
<!--experiment 2 -->
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Content, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" Value="0">
<Setter Property="Background" Value="LimeGreen"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>

Odpowiedzi:

0 dla odpowiedzi № 1

Wystarczy użyć konwertera wartości (z wartością komórki jako parametru), który zwraca żądany kolor.

<DataGrid>
<DataGridCell Background="{Binding CellValueField, Converter={StaticResource YourDefinedValueToColorConverter}}" />
</DataGrid>

EDYTUJ: W końcu udało się.

Definicje konwertera i stylu:

<Window.Resources>
<c:ValueToColorConverter x:Key="ValueToColorConverter"/>
<Style x:Key="CellStyle" TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToColorConverter}}" />
</Style>
</Window.Resources>

DataGrid:

<DataGrid HorizontalAlignment="Left"
Margin="10,10,0,0"
VerticalAlignment="Top"
Loaded="DataGrid_Loaded">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding Converter={StaticResource ValueToColorConverter}}" />
</Style>
</DataGrid.CellStyle>
</DataGrid>

A konwerter:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var cell = value as Order;
if (cell != null && cell.Size > 80)
return new SolidColorBrush(Colors.Red);
else return new SolidColorBrush(Colors.Yellow);
}

Użyłem DataGrid_Loaded metoda wypełnienia siatki danych danymi losowymi zamkniętymi w klasie przykładowej

class Order
{
public int Size { get; set; }
}

A wynik:

wprowadź opis obrazu tutaj


0 dla odpowiedzi nr 2

Użyj konwertera wartości, takiego jak ten:

<DataGridCell Background="{Binding CellValueField, Converter={StaticResource IntegerToColorValueConverter}}" />

I:

public class IntegerToColorValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
switch ((int)value)
{
case 1: return Color.Red; break;
case 2: return Color.Yellow; break;
Default: return Color.White; break;
}
}

}