开发者

Binding Style to DataGridTextColumns ElementStyle

开发者 https://www.devze.com 2023-04-09 08:04 出处:网络
I have a datagrid with some objects. The objects have a name, a \"type\" property and a bunch of irrelevant properties.

I have a datagrid with some objects. The objects have a name, a "type" property and a bunch of irrelevant properties.

based on if the type is "MaterialType" or not i want to set a style for the cells textblock (bold & intend 10px)

I started out with a converter. => it gets the type and converts to a font-weight.

<DataGridTextColumn.ElementStyle>
    <Style TargetType="TextBlock">
        <Setter Property="FontWeight" Value="{Binding type, Converter={StaticResource ResourceKey=TypeToFontWeightConverter}}"/>
        <Setter Property="Padding" Value="10,0,0,0"/>
    </Style>
</DataGridTextColumn.ElementStyle>

It works.. but I only got to set the font-weight.

I want an individual style.

so I edited my converter into a TypeToStyle Converter

    class TypeToStyleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            Style style = new Style(typeof(TextBlock));

            if (value is Type && value == typeof(MaterialType))
            {
                style.Setters.Add(new Setter(TextBlock.FontWeightProperty, FontWeights.Bold));
                style.Setters.Add(new Setter(TextBlock.PaddingProperty, new Thickness(0)));
            }
            else
            {
                style.Setters.Add(new Setter(TextBlock.FontWeightProperty, FontWeights.Bold));
                style.Setters.Add(new Setter(TextBlock.PaddingProperty, new Thickness(10,0,0,0)));
            }
            return style;
        }

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

        #endregion
    }

Then I bind the converter.

<DataGridTextColumn Binding="{Binding Name}"
                    Header="Name"
                    IsReadOnly="True"
                    Width="1*"
                    ElementStyle="{Binding type, Converter={StaticResource ResourceKey=TypeToSt开发者_运维技巧yleConverter}}"/>

It all compiles fine. But no styles. The converter doesn't get triggered...


I think you want to look into using a StyleSelector instead of a Converter.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号