Chanakya
Chanakya

Reputation: 178

Precedence of multiple styles for the same target type?

If there are multiple styles like this:

<Style TargetType="{x:Type local:MyControl}">
...

that are merged in from resource dictionaries that target the same type of control, which should have precedence, is it the first style encountered or last one?

Where can I find the rules that govern such things?

Upvotes: 1

Views: 2372

Answers (3)

Mangesh
Mangesh

Reputation: 5861

It will throw an exception. This is what I tried to test this:

I wrote a simple ResourceDictionary with 2 styles, with same TargetType but without x:Key (not x:Name).

<Style TargetType="TextBox">
    <Setter Property="Height" Value="100"/>
</Style>

<Style TargetType="TextBox">
    <Setter Property="Height" Value="200"/>
</Style>

Rebuilt the project and it complied successfully. Now which will get applied?

Well, when I ran it, it threw a big exception when loading the styles. So in short, it doesn't work.

Upvotes: 0

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

This is the answer for your comment and for question at all. Name, x:Name doesn't play on the scene in this case. Each resource in the dictionary must have the Key. For targeted styles WPF infrastructure generates the Key, so, the styles with the same target type will have same key, thus you can't use more than one targeted style for each type in the dictionary.

Upvotes: 2

Troels Larsen
Troels Larsen

Reputation: 4651

Styles are applied from the ResourceDictionary closest to the control in question. An example:

 <Window>
    <Window.Resource>
        <Style 1/>
    <Window.Resources>
    <Grid>
        <Grid.Resources>
            <Style 2/>
        </Grid.Resources>
        <TextBox/>
    </Grid>
</Window>

In the above example, Style 2 will be applied to the TextBox. Should you wish to cascade the styles (apply both styles to the TextBox), you can set BasedOn on Style2 to point to Style1 using BasedOn="{StaticResource {x:Type TextBox}}". Please check the syntax, I don't have VS here.

As you can see, the type becomes the Key. Since it is not permissible to have two elements with the same key in a single ResourceDictionary, you cannot merge two ResourceDictionaries with overlapping styles. It should be possible to design around such a requirement, remembering that a ResourceDictionary can reference another use. Again, you use BasedOn.

Upvotes: 4

Related Questions