¿Cómo asignar un estilo de recurso dinámico en el código?


Quiero producir en código el equivalente de esto en XAML:

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

Puedo hacer el texto y el ancho, pero cómo puedo asignar el recurso dinámico al estilo:

TextBlock tb = new TextBlock();
            tb.Text = "Title:";
            tb.Width = FormLabelColumnWidth;
            tb.Style = ???
Author: Dave Clemmer, 2009-11-18

3 answers

Puedes probar:

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

Disfrute!

 30
Author: Alastair Pitts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-18 09:10:05

Debe usar FrameworkElement.SetResourceReference si desea un verdadero comportamiento de DynamicResource, es decir, actualizar el elemento de destino cuando cambie el recurso.

tb.SetResourceReference(Control.StyleProperty, "FormLabelStyle")
 149
Author: Samuel Jack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-18 09:13:28

Esto debería funcionar:

tb.SetValue(Control.StyleProperty, "FormLabelStyle");
 3
Author: robert.oh.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-04 12:50:42