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.
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.
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