Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a dynamic resource style in code?

I want to produce in code the equivalent of this in XAML:

<TextBlock Text="Title:" Width="{Binding FormLabelColumnWidth}" Style="{DynamicResource FormLabelStyle}"/> 

I can do the text and the width, but how do I assign the dynamic resource to the style:

TextBlock tb = new TextBlock();             tb.Text = "Title:";             tb.Width = FormLabelColumnWidth;             tb.Style = ??? 
like image 656
Edward Tanguay Avatar asked Nov 18 '09 09:11

Edward Tanguay


People also ask

What is DynamicResource in Xamarin forms?

The DynamicResource markup extension is similar to the StaticResource markup extension in that both use a dictionary key to fetch a value from a ResourceDictionary . However, while the StaticResource performs a single dictionary lookup, the DynamicResource maintains a link to the dictionary key.

What are dynamic resources in WPF?

Utilizing WPF Resources 2. 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.


2 Answers

You should use FrameworkElement.SetResourceReference if you want true DynamicResource behaviour - ie updating of the target element when the resource changes.

tb.SetResourceReference(Control.StyleProperty, "FormLabelStyle") 
like image 66
Samuel Jack Avatar answered Oct 12 '22 13:10

Samuel Jack


You can try:

tb.Style = (Style)FindResource("FormLabelStyle"); 

Enjoy!

like image 45
Alastair Pitts Avatar answered Oct 12 '22 13:10

Alastair Pitts