Get the control style {StaticResource {x: TextBlock type}} in the code behind

I want to get the default Style for the TextBlock in the code without adding the default TextBlock Style to the resources in XAML .

I have a method like this:

 public TextBlock DrawTextBlockAtPoint(string text, Style style) { //... } 

that I want to provide an override that uses the usual TextBlock Style :

 public TextBlock DrawTextBlockAtPoint(string text) { var style = GetDefaultStyleForProperty(TextBlock.StyleProperty); DrawTextBlockAtPoint(text, style) } 

Is there any way to do this?

+4
source share
1 answer

StaticResource The markup extension essentially attempts to find a resource for the define key. If the default style for the TextBlock type can be obtained using: {StaticResource {x:Type TextBlock}} , you can get it in the code using:

 var defaultTextBlockStyle = FindResource(typeof(TextBlock)); 

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

Hope this helps.

+8
source

All Articles