Gerard
Gerard

Reputation: 13407

TemplateBinding gives error DependencyProperty.UnsetValue

I am having trouble to understand why a {DependencyProperty.UnsetValue} occurs and to be honest also what it exactly means. I have a case with "borrowed code" that works perfectly well in the original solution but not in my project.

There are three style definitions:

<Style TargetType="Button" BasedOn="{StaticResource {x:Type ButtonBase}}" />
<Style TargetType="c:DropDownButton" BasedOn="{StaticResource {x:Type ButtonBase}}" />
<Style TargetType="{x:Type ButtonBase}">
....
<Setter Property="Background" Value="{StaticResource ButtonBrush}" />
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="ButtonBase">
            <Border x:Name="PART_border"
                    ....
                    Background="{TemplateBinding Background}"
                    Padding="{TemplateBinding Padding}">
                <ContentPresenter RecognizesAccessKey="True"
                                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                   orizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Background="{TemplateBinding Background}" gives the error, with a hard-coded color it works as expected.
When I deactivate <!--<Setter Property="Background" Value="{StaticResource ButtonBrush}"/>--> the exception occurs too, however only after the app has loaded and is visible. Isn't that rather strange?

I cannot figure out why the original project doesn't have this issue.
Solution was: wpf must find the brushes before it applies the style.
In my case I moved the Brushes in use before the Style definition.
I understand the "strange behavior" above as that wpf applies the brushes at a later point in time and hence throws the exception at a later point.

Upvotes: 0

Views: 1206

Answers (1)

eran otzap
eran otzap

Reputation: 12533

If your brush is placed in a different Resource Dictionary it does recognize that such a key exists in your app at compile time but as i understand it there is no guarantee to when the resource is applied .

use a DynamicResource in this case to solve the problem .

Upvotes: 2

Related Questions