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 = ???
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.
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.
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")
You can try:
tb.Style = (Style)FindResource("FormLabelStyle");
Enjoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With