Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set control Background color using Dynamic Resource in WPF?

Tags:

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

like image 375
iAteABug_And_iLiked_it Avatar asked Jul 06 '13 11:07

iAteABug_And_iLiked_it


1 Answers

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.

like image 62
Anatoliy Nikolaev Avatar answered Sep 23 '22 16:09

Anatoliy Nikolaev