Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply a dynamic style in code at runtime?

Tags:

.net

styling

wpf

I need to apply a style in code ike this:

TextBlock.Style = TryFindResource("MyStyle") as Style;

that will be updated dynamically when the resource dictionary is changed (i.e. skin is replaced at runtime). In other words I need the equivalent to using a dynamic resource like this:

<TextBlock Style="{DynamicResource MyStyle}" />
like image 392
Micah Avatar asked Dec 04 '08 18:12

Micah


People also ask

How to apply style dynamically in JavaScript?

By calling element. style. color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id .

Can we change dynamics resources at run time?

Dynamic Resource - Dynamic resources are the resources which you can manipulate at runtime and are evaluated at runtime. If your code behind changes the resource, the elements referring resources as dynamic resources will also change.

Which function is used to add CSS styles to dynamically added controls?

To add CSS properties dynamically, we use css() method. The css() method is used to change style property of the selected element.

How can the style of an element be modified?

Note that you can also change style of an element by getting a reference to it and then use its setAttribute method to specify the CSS property and its value. Be aware, however, that setAttribute removes all other style properties that may already have been defined in the element's style object.


1 Answers

Try using SetResourceReference.

textBlock.SetResourceReference(TextBlock.StyleProperty, "MyStyle")
like image 63
David Padbury Avatar answered Sep 23 '22 15:09

David Padbury