Binding Setter value to DynamicResource
Asked Answered
M

1

6

I'm creating triggers in code behind and I'm attempting to bind the value of a setter to a dynamic resource created in the code behind as well so I can update the resource whenever and still have the value of the setter updated. I'm as far as this

SolidColorBrush brush = Brushes.Red;
Resources.Add("NewBrush",brush);
Setter setter = new Setter();
setter.Property = Control.BackgroundProperty;

but I'm unsure how to bind the value of the setter to the Dynamic Resource created. I can't simply create the resource in XAML because the resource needs to be created dynamically. How do I bind the value of the Setter to the dynamic resource so changing the resource will alter the value of the setter.

A little more information to clarify. This is all done in code behind because everything is generated dynamically. Triggers, setters, formatting, controls are all being created based off an XML structure.

Millican answered 12/3, 2013 at 15:39 Comment(3)
I can't simply create the resource in XAML because the resource needs to be created dynamically - That's no reason not to define the Setter in XAML.Martin
@HighCore I attempted to clarify aboveMillican
can you post an example of the XML file?Martin
D
9

Some decompilation using ILSpy helped solve this:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();

            var style = new Style(typeof (Button));

            var brush = new SolidColorBrush(Colors.Blue);

            Resources["TheColor"] = brush;
            var dynamicResource = new DynamicResourceExtension("TheColor");

            var setter = new Setter()
                {
                    Property = Control.BackgroundProperty,
                    Value = dynamicResource
                };
            style.Setters.Add(setter);

            button1.Style = style;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            var brush = new SolidColorBrush(Colors.Red);

            Resources["TheColor"] = brush;
        }
    }

So interestingly, the Setter.Value expects a value of DynamicResourceExtension. I originally thought that the expression generated by DynamicResourceExtension.ProvideValue() would be what the setter value should take. Anyway, this seems to work.

Diplomate answered 12/3, 2013 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.