This is my XAML
<Grid.Resources>             <SolidColorBrush x:Key="DynamicBG"/> </Grid.Resources> <Label name="MyLabel" Content="Hello" Background="{DynamicResource DynamicBG} />   So I have two questions:
Q1: How do I go about setting the DynamicBG key value to Red in my code now? (When the window loads, I'd like to set it to red)
Q2: Is this how dynamic resources are supposed to be used?
Thank you
To gain access to the Resource of the code must identify them in the file App.xaml:
<Application.Resources>     <SolidColorBrush x:Key="DynamicBG" /> </Application.Resources>   XAML example
<Grid>            <Label Name="MyLabel"             Content="Hello"             Background="{DynamicResource DynamicBG}" />      <Button Content="Change color"             Width="100"              Height="30"              Click="Button_Click" /> </Grid>   The Resource can be changed in code line of the form:
Application.Current.Resources["MyResource"] = MyNewValue;   Example:
Code behind
// using ContentRendered event private void Window_ContentRendered(object sender, EventArgs e) {     SolidColorBrush MyBrush = Brushes.Aquamarine;      // Set the value     Application.Current.Resources["DynamicBG"] = MyBrush;          }  private void Button_Click(object sender, RoutedEventArgs e) {     SolidColorBrush MyBrush = Brushes.CadetBlue;      // Set the value     Application.Current.Resources["DynamicBG"] = MyBrush; }   Principle, DynamicResources were designed, so they can be changed. Where to change - it is the task of the developer. In the case of Color, it is one of the most common methods. See the MSDN, for more information.
P. S. I recommend using App.xaml, because there have been cases where a StaticResource has been used successfully, but not DynamicResource (resources are placed in the Window.Resources). But after moving the resource in App.xaml, everything started 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