Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Converter in DataGridCell

Tags:

c#

wpf

xaml

I am trying to create converter that shows me if something got value is Other then "None" just write X in cell so I have created simple element style:

<DataGridTextColumn.ElementStyle>
   <Style TargetType="{x:Type TextBlock}">
   <Setter Property="Text" Value="{Binding Value, Converter={StaticResource SetBitConverter}}"/>
   </Style>
</DataGridTextColumn.ElementStyle>

And converter is as well simple

public class SetBitConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var input = value as string;

        switch (input)
        {
            case "None":
                return "OK";
            default:
                return "X";
        }
    }

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

Now problem is that on value set it will not enter converter, although if i change property from Text to Background for example, it will enter converter with no problem.

like image 451
Wojciech Szabowicz Avatar asked Mar 02 '26 12:03

Wojciech Szabowicz


1 Answers

The value applied by a Style will always be of lower priority than one that has been set directly or, as in your case, by a Binding. If you want to add a Converter, add it to the Binding property of the DataGridTextColumn or use a DataGridTemplateColumn instead.

E.g.:

<DataGridTextColumn Binding="{Binding Value, Converter={StaticResource SetBitConverter}}"/>

Here is a comparison of the auto-generated default column and the one from above:

Comparison


Why does dependency property precedence exist?
Typically, you would not want styles to always apply and to obscure even a locally set value of an individual element (otherwise, it would be very difficult to use either styles or elements in general). Therefore, the values that come from styles operate at a lower precedent than a locally set value.

Technical Background on Value Precedence

  1. Property system coercion
  2. Active animations, or animations with a Hold behavior
  3. Local value
  4. TemplatedParent template properties
  5. Implicit style
  6. Style triggers
  7. Template triggers
  8. Style setters
  9. Default (theme) style
  10. Inheritance
  11. Default value from dependency property metadata
like image 169
Manfred Radlwimmer Avatar answered Mar 05 '26 01:03

Manfred Radlwimmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!