Get the Style of a Control {StaticResource {x:Type TextBlock}} in code behind

code-behind, default, styles, wpf

Solution

The StaticResource Markup Extension essentially tries to find a resource for the defines key. If the default style for the TextBlock type can be retrieved using: `{StaticResource {x:Type TextBlock}}` you should be able to get it in code using:

var defaultTextBlockStyle = FindResource(typeof(TextBlock));

Of course, this needs to be called in a context in which the FindResource methods is defined. I used it inside my main Window class and it works.

Hope this helps.

Problem

I want to grab the default `Style` for a `TextBlock` in code behind without ever having adding a custom default `TextBlock` `Style` to resources in `XAML`. I've got a method like this: ``` public TextBlock DrawTextBlockAtPoint(string text, Style style) { //... } ``` that I want to provide an override that just uses the regular `TextBlock` `Style`: ``` public TextBlock DrawTextBlockAtPoint(string text) { var style = GetDefaultStyleForProperty(TextBlock.StyleProperty); DrawTextBlockAtPoint(text, style) } ``` Is there anyway to do this?

Original source