wpf - examples - Cómo establecer el fondo de fila de DataGrid, basado en un valor de propiedad utilizando enlaces de datos
wpf datagrid binding (2)
Lo mismo se puede hacer sin DataTrigger también:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" >
<Setter.Value>
<Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
<Binding.ConverterParameter>
<x:Array Type="SolidColorBrush">
<SolidColorBrush Color="{StaticResource RedColor}"/>
<SolidColorBrush Color="{StaticResource TransparentColor}"/>
</x:Array>
</Binding.ConverterParameter>
</Binding>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowStyle>
Donde BooleanToBrushConverter es la siguiente clase:
public class BooleanToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return Brushes.Transparent;
Brush[] brushes = parameter as Brush[];
if (brushes == null)
return Brushes.Transparent;
bool isTrue;
bool.TryParse(value.ToString(), out isTrue);
if (isTrue)
{
var brush = (SolidColorBrush)brushes[0];
return brush ?? Brushes.Transparent;
}
else
{
var brush = (SolidColorBrush)brushes[1];
return brush ?? Brushes.Transparent;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
En mi código XAML, quiero establecer el color de Background de cada fila, en función de un valor del objeto en una fila específica. Tengo una ObservableCollection de z , y cada una de las z tiene una propiedad llamada State . Empecé con algo como esto en mi DataGrid :
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background"
Value="{Binding z.StateId, Converter={StaticResource StateIdToColorConverter}}"/>
</Style>
</DataGrid.RowStyle>
Este es un enfoque incorrecto porque x no es una propiedad en mi clase ViewModel.
En mi clase ViewModel tengo un ObservableCollection<z> que es el ItemsSource de este DataGrid , y un SelectedItem del tipo z .
Podría vincular el color a SelectedItem , pero esto solo cambiará una fila en DataGrid .
¿Cómo puedo, en base a una propiedad, cambiar este color de fondo de filas?
Use un DataTrigger :
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>