How to assign a dynamic resource style in code?

Edward Tanguay picture Edward Tanguay · Nov 18, 2009 · Viewed 58.3k times · Source

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 = ???

Answer

Samuel Jack picture Samuel Jack · Nov 18, 2009

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")