简体   繁体   中英

How to access DataGridCell Binding Value in Style Resource

I want to reuse a DataGridCell Style from a resource file in my whole application, to show negative values in red. The problem is, that the value that gets passed to the converter is the parent instance of the class instead of the value of the bound property.

The Grid Columns look like this:

<DataGridTextColumn Header="7 T %" Binding="{Binding Item.V7P, StringFormat=p}" CellStyle="{StaticResource ProzentZelle}"/>
<DataGridTextColumn Header="14 T %" Binding="{Binding Item.V14P, StringFormat=p}" CellStyle="{StaticResource ProzentZelle}"/>
<DataGridTextColumn Header="21 T %" Binding="{Binding Item.V21P, StringFormat=p}" CellStyle="{StaticResource ProzentZelle}"/>
<DataGridTextColumn Header="28 T %" Binding="{Binding Item.V28P, StringFormat=p}" CellStyle="{StaticResource ProzentZelle}"/>

The Style Resoucre looks like this:

<con:GtZeroConverterx:Key="G0C"/>

<Style x:Key="ProzentZelle" TargetType="DataGridCell">
    <Setter Property="HorizontalAlignment" Value="Right"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=., Converter={StaticResource G0C}}" Value="True">
            <Setter Property="Foreground" Value="Red"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

The Converter code:

internal class GtZeroConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //value is actually the Item and not one the property passed to Binding
        if (System.Convert.ToDecimal(value) >= 0)
        {
            return true;
        }
        else
        {
            return false;
        }

    }

}

If Item.V7P is 0.75 I want to receive 0.75 as value in the converter not the Item itself. How can I access the property bound to the datagridcell instead of the whole instance?

How can I access the property bound to the datagridcell instead of the whole instance?

By binding to the property instead of the "whole instance":

<DataTrigger Binding="{Binding Path=Item.V7P, Converter={StaticResource G0C}}" Value="True">
        <Setter Property="Foreground" Value="Red"/>
</DataTrigger>

And yes, this unfortunately means that you will have to create a template per column since you cannot inject only the binding path and reuse the rest of the template in pure XAML.

An option would be to create a template per column programmatically using the XamlReader.Parse method. You could then define the template as a XAML string and use string.Replace or similar to "inject" the binding path into it programmatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM