How can I style a DataGridCell's content based on binding without naming that binding

纵饮孤独 提交于 2019-11-28 14:28:49

here is a solution for DataGridTextColumns. DataGridTextColumn creates TextBlock element to display cell value. TextBlock has string Text property. Those TextBlocks can be accessed via DataGridCell Content property, so resulting binding path is "Content.Text"

<Style.Triggers>
    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, 
                 Path=Content.Text, Mode=OneWay,
                 Converter={StaticResource greaterThanZeroDecimalConverter}}" 
                 Value="True">
        <Setter Property="Foreground" Value="Green"/>
    </DataTrigger>
    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, 
                 Path=Content.Text, Mode=OneWay,
                 Converter={StaticResource greaterThanZeroDecimalConverter}}" 
                 Value="False">
        <Setter Property="Foreground" Value="Red"/>
    </DataTrigger>
    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, 
                 Path=Content.Text, Mode=OneWay}" 
                 Value="0">
        <Setter Property="Foreground" Value="Black"/>
    </DataTrigger>
</Style.Triggers>

note {RelativeSource Self}.

I also had to change Convert method because Text is a string property and incoming value is string.

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    double d;
    if (value != null && value is string && double.TryParse(value.ToString(), out d))
    {
        return d > 0;
    }
    return null;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!