14

In WPF, you can create a Style that acts as the default for a control type in XAML:

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

Then, when WPF goes to display that control, it looks up that Style from the resources based on the its type.

I want to do the equivalent of this in the code-behind of my program. How do I find that Style?

Tim Pohlmann
  • 4,140
  • 3
  • 32
  • 61
Tony Vitabile
  • 8,298
  • 15
  • 67
  • 123

2 Answers2

32

You can search for the style in the Application-level resources by using the control type as the key:

Style defaultStyle = Application.Current.TryFindResource(typeof(MyControl)) as Style;
Core
  • 601
  • 2
  • 7
  • 19
ZF.
  • 636
  • 7
  • 15
4

object globalStyleDefinedByApp;
Style globalStyle = new Style(typeof(TargetType));
if (Application.Current.Resources.TryGetValue(typeof(TargetType), out globalStyleDefinedByApp))
{
    globalStyle = globalStyleDefinedByApp as Style ?? globalStyle;
}

In case somebody lands here looking for a solution for Universal Windows Projects (UWP), no TryFindResource exists so the above is how you have to do it.

bc3tech
  • 1,228
  • 14
  • 27