Gerard
Gerard

Reputation: 13397

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.

Upvotes: 0

Views: 82

Answers (2)

nkoniishvt
nkoniishvt

Reputation: 2521

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.

Upvotes: 1

ZSH
ZSH

Reputation: 913

In the control template you need to bind the data to the control properties i.e the TextBoxEx and when you use the control and bind it to a DataContext you pass the data to the control template via the control , when you set Foreground to blue in the control template you brake the pipe and the control color will be blue no matter what you do
DataContext -> Control -> ControlTemplate
when you set the blue in the control template you cut the second arrow
DataContext -> Control XXXXX ControlTemplate
so the blue is blue no matter what you are doing
see MSDN ControlTemplate for more info

Upvotes: 0

Related Questions