Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF pass object to datagrid's converter and change color of one cell

Tags:

c#

wpf

datagrid

currently I am trying to make converter, that changes background color of one cell in DataGrid's row. Each row represents one CustomTask object. Now my converter changes backroung of entire row. It's not what I want, I need to change background of only one chosen cell.

My xaml:

<DataGrid x:Name="customTasksDataGrid" Margin="10,10,10,38" Grid.Column="1" IsReadOnly="True" AutoGenerateColumns="False">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="{Binding Path=., Converter={StaticResource converter}}" />
        </Style>
    </DataGrid.RowStyle>
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Foo" Binding="{Binding Foo}"/>
        <DataGridTextColumn Header="Bar" Binding="{Binding Bar}"/>
        ...
    </DataGrid.Columns>
</DataGrid>

My converter:

[ValueConversion(typeof(DataRowView), typeof(Brush))]
public class DateToBrushConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return null;
        CustomTask t = (CustomTask)value;
        return new SolidColorBrush(Color.FromArgb(255,0,0,120));
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Changing color of entire row roks perfectly now. How to change for example Bar cell background color depending on Foo value?

like image 382
Marcin Zdunek Avatar asked Dec 06 '25 05:12

Marcin Zdunek


1 Answers

You need to specify the TextColumn style individually, not the entire row.

<DataGrid x:Name="customTasksDataGrid" Margin="10,10,10,38" Grid.Column="1" IsReadOnly="True" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Foo" Binding="{Binding Foo}"/>
        <DataGridTextColumn Header="Bar" Binding="{Binding Bar}">
            <DataGridTextColumn.ElementStyle>
                <Style TargetType="{x:Type TextBlock}">
                    <Setter Property="Background" Value="{Binding Path=., Converter={StaticResource converter}}"/>
                </Style>
            </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>
like image 157
d.moncada Avatar answered Dec 09 '25 02:12

d.moncada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!