views:

526

answers:

3

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 = ???
+2  A: 

This should work:

tb.SetValue(Control.StyleProperty, "FormLabelStyle");

HTH

robert.oh.

robert.oh.
+2  A: 

You can try:

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

Enjoy!

Alastair Pitts
+3  A: 

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