0

In this answer it is being (correctly? it seems..) claimed thant if you omit the x:Name attribute the style is automatically applied everywhere.

If you don't specify an identifier on each Style, that style will apply to all controls that match with the TargetType you specified. If you want button to look different, you can do the same as above, but also include an identifier to that style, that will be used by each different button: [...]

However, when I add a x:Name indentifier, it should not be automatically applied, or should it?

Because when I try this:

<Style TargetType="{x:Type TextBlock}" x:Name="RunningTextStyle">
    <Setter Property="FontSize" Value="15" />
</Style>

in my ResourceDictionary that is linked into my app.xaml this way:

<Application.Resources>
    <ResourceDictionary Source="ApplicationStyles.xaml" />
</Application.Resources>

It does still automatically apply to all TextBlocks.

How do I create a style that has to be used with its indentifier to show up?

I use Resharper in VS2015 and the x:Key name doesn't even show up when I try to add the style to a TextBlock manually this way: Style="{StaticResource ...}" definition as a possibility (I had it once this way and it did. It works, but normally it's being advertised by R# or VS to be used).

Interestingly enough, I had just a few hours before the other way around, where my Button style wasn't automatically applied.

Community
  • 1
  • 1
Mafii
  • 7,227
  • 1
  • 35
  • 55

2 Answers2

3

Give the Style an x:Key="MyArbitraryStyleKey" property. It's in a ResourceDictionary, and the "name" (figuratively, so to speak) of a thing in a dictionary is called a Key, which does actually make sense when you look at it that way. And functionally, in XAML, x:Name and x:Key invoke different code to do different things in very different ways, even if the semantic difference feels a bit fuzzy at first.

<Style TargetType="{x:Type TextBlock}" x:Key="RunningTextStyle">
    <Setter Property="FontSize" Value="15" />
</Style>

...

<TextBlock 
    Style="{StaticResource RunningTextStyle}" 
    Text="I tried Resharper once. Sent them back their demo, tied to a brick."
    />

If Resharper doesn't like it, send them a bug report (hey, turns out Resharper likes it fine -- I take back everything I said!)

3

Just use x:Key="RunningTextStyle" insted of x:Name="RunningTextStyle"

Whencesoever
  • 2,218
  • 15
  • 26
  • 1
    I accepted Ed's answer because it was more detailed, and because he was 2 minutes faster. You're answer is just as correct (and more straight to the point!), thank you for your help. – Mafii Jul 12 '16 at 14:22