简体   繁体   中英

Applying Style to DataGridCell programmatically with Converter

I need to apply this XAML style to DataGrid's Cell via code:

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Self}, Path=Item.Dif, Converter={StaticResource RedValues}}"/>
    </Style>
</DataGrid.RowStyle>

So far on my code I can apply a Setter on the TextAlignmentProperty but not on the foreground:

Style style2 = new Style(typeof(DataGridCell));
style2.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));
style2.Setters.Add(new Setter(TextBlock.ForegroundProperty, new RedValues()));

codb = new DataGridTextColumn();
codb.Binding = new Binding("Dif") {
    StringFormat = "C",
    ConverterCulture = new CultureInfo("pt-PT") };
codb.Header = "Dif";
codb.CellStyle = style2;
grid.Columns.Add(codb);

And this is my Converter Class:

class RedValues: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is decimal) {
                decimal quantity = (decimal)value;
                if (quantity < 0)
                    return Brushes.IndianRed;
                if (quantity > 0)
                    return Brushes.ForestGreen;
                return Brushes.Black; 
            }

            return Brushes.Yellow;
        }

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

You can do something like this if you want to assign a binding with converter from code ..

style2.Setters.Add(new Setter(TextBlock.ForegroundProperty, new Binding("Item.Dif"){Converter = new RedValues()} ))};

for your case -- you may add all your relative code and path bindings as you feel like ..

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