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

1

5

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?

Saddle answered 10/9, 2009 at 18:39 Comment(0)
B
9

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.

Bade answered 11/9, 2009 at 17:39 Comment(1)
This helped a lot: typeof and using the container where the style was declared (my case was a StackPanel, previously I used FindResource on the Window and it wasn't working).Money

© 2022 - 2024 — McMap. All rights reserved.