Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does x:Key="{x:Type TextBox}" do?

Tags:

syntax

wpf

xaml

Everything is in the title:

I've read more than once that setting a style like this:

<Style TargetType="TextBox">...</Style>

was roughly equivalent to:

<Style x:Key="{x:Type TextBox}" TargetType="TextBox">...</Style>

(last time in a comment on another question)

both should apply the style to all textBoxes in the app (if they are put in the app's resources of course)

but I tried both in my apps, and only the second one with the x:Key defined works.

it seams quite logical for me, since the first one does not know where to be applied without any x:Key property set, but then what is the point of the first syntax?

Edit: example of code in my app that works fine:

<Style x:Key="{x:Type ComboBoxItem}" TargetType="{x:Type ComboBoxItem}">
     <Setter Property="HorizontalContentAlignment" Value="Left"/>
     <Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>

and code that doesn't:

<Style TargetType="{x:Type ComboBoxItem}">
     <Setter Property="HorizontalContentAlignment" Value="Left"/>
     <Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>

I wrote this to get rid of the binding issues you get with comboBoxItems when you manipulate an existing ComboBox's itemsSource. And the first code works fine, but the second one does not.

you can see this easily by setting the horizontalContentAlignment to Right

Edit 2: This code is simply put in a resource dictionary in my App.xaml. And replacing TargetType="{x:Type ComboBoxItem}" with TargetType="ComboBoxItem" makes no difference whatsoever

Edit 3: I just realized I might have forgotten to precise something important (sorry about that): though the styles are defined in xaml, I actually add the controls to the layout in my code behind as they are added dynamically. Might be where the trouble lies...

like image 939
David Avatar asked Feb 01 '11 08:02

David


1 Answers

As shown in the first example above, setting the TargetType property to TextBlock without assigning the style with an x:Key allows your style to be applied to all TextBlock elements. What actually happens is that doing so implicitly sets the x:Key to {x:Type TextBlock}. This also means that if you give the Style an x:Key value of anything other than {x:Type TextBlock}, the Style would not be applied to all TextBlock elements automatically. Instead, you need to apply the style to the TextBlock elements explicitly.

Considering that this is from the official documentation, your issue has to be an anomaly. I have seen a few such oddities and they are not all too unexpected since the coding behind WPF is bound to be imperfect.

(Is there a difference in outcomes between TargetType="ComboBoxItem" and TargetType="{x:Type ComboBoxItem}" if the key is omitted?)

like image 166
H.B. Avatar answered Oct 16 '22 03:10

H.B.