You saw that static resource is not appropriate for some
scenarios when you want to have a result that can be updated for changes in
other elements. In order to solve this you can use dynamic resources.
Listing 3, Listing 4 and Figure 1 use dynamic resources to
show how they work. I used a dynamic resource to track all changes for the
background color of my Window and set myButton background to it. Once this
value changes, myButton must get the same background. Listing 5 shows the
simple code I used to change the background of the Window when the user clicks
on a button.
Listing 3
<Window x:Class="ResourcesInXAML.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Resources In XAML" Height="200" Width="300"
>
<Window.Resources>
<SolidColorBrush x:Key="myBrush" Color="GreenYellow" />
</Window.Resources>
<StackPanel Margin="30">
<Button Background="{DynamicResource Window1.Background}"
Width="200" Height="40" Name="myButton">
ASP Alliance
</Button>
<Button Click="OnClick" Width="200" Height="40">
Change Background
</Button>
</StackPanel>
</Window>
Listing 4
public void OnClick(object sender, RoutedEventArgs args)
{
this.Background = Brushes.GreenYellow;
}
Figure 1
