Wojciech Szabowicz
Wojciech Szabowicz

Reputation: 4198

WPF Converter in DataGridCell

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.

Upvotes: 3

Views: 2360

Answers (1)

Manfred Radlwimmer
Manfred Radlwimmer

Reputation: 13394

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

Upvotes: 6

Related Questions