Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid Trigger on cell content

I have a datagrid than contains value comes from a stored procedure. All values are set Bold as FontWeight.

I'd like to make the text normal when the cell content is equal to 0.

How can I do that with a trigger?

I've done it like below but it's not working:

<DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
            <Setter Property="FontWeight" Value="Bold" />
            <Style.Triggers>
                <Trigger Property="Content" Value="0">
                    <Setter Property="FontWeight" Value="Normal"/>
                </Trigger>
            </Style.Triggers>
    </Style>
</DataGrid.CellStyle>
like image 211
Galma88 Avatar asked Jun 17 '15 08:06

Galma88


1 Answers

You can't access DataGridCell.Content that way, use a DataTrigger instead based on your DataGrid.SelectedItem.YourProperty like this:

    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="FontWeight" Value="Bold" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding YourProperty}" Value="0">
                    <Setter Property="FontWeight" Value="Normal"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.CellStyle>

EDIT:

Assuming your DataGridColumns are text-based then you can use an IValueConverter as below:

Note that if some of data-grid columns are not text-based, this solution still works for those columns which are.

Xaml:

<Window.Resources>
    <local:FontWeightConverter x:Key="fontWeightConverter"/>
</Window.Resources>

...

    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Setters>
                <Setter Property="FontWeight" 
                       Value="{Binding RelativeSource={RelativeSource Self}, 
                       Path=Content.Text, 
                       Converter={StaticResource fontWeightConverter}}" />
            </Style.Setters>
        </Style>
    </DataGrid.CellStyle>

Converter:

public class FontWeightConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        if (value != null && value.ToString() == "0")
            return FontWeights.Normal;
        return FontWeights.Bold;
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
like image 121
Bahman_Aries Avatar answered Nov 15 '22 14:11

Bahman_Aries