Search code examples
wpfxamlpropertiesoperator-precedence

Property set in a style cannot be overruled with binding in xaml?


The following control definition works ok:

<local:TextBoxEx Text="{Binding Title, UpdateSourceTrigger=PropertyChanged, Delay=900}"
                 Foreground="{Binding Selection.Error, Converter={StaticResource BoolToErrorBrush}}"/>

When I change it using a style:

<Style x:Key="TextBoxTitle" TargetType="local:TextBoxEx">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <local:TextBoxEx Text="{Binding Text, RelativeSource={RelativeSource TemplatedParent}, UpdateSourceTrigger=PropertyChanged}"
                                 Foreground="Blue"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<local:TextBoxEx Text="{Binding Title, UpdateSourceTrigger=PropertyChanged, Delay=900}" 
                 Style="{StaticResource TextBoxTitle}" 
                 Foreground="Pink"/>

The binding to Title overrules the style binding to Text and works.
Setting the Foreground color has no effect, it is still blue. When I use Foreground="{TemplateBinding Foreground}" in the controltemplate style it works.

I cannot understand this behaviour, can you?
In the first case the local definition is leading, in the second case it is not.


Solution

  • I don't see what is wrong here. The RelativeSource to the TemplatedParent will look for the Text property in the original component at runtime, which property is bound to Title. It's intrinsically equivalent to a TemplateBinding to Text (but it's slower).

    About the Foreground, it'll always be blue except if you use a TemplateBinding in which case it'll take the color you defined in the TemplatedParent.

    I don't understand your problem here.