I have a question that has me confused. I am studying for my MCP (test 70-511 Windows App. Dev. with .Net 4) and I am on the section of resources and changing resources in code. Here is a quote directly from the book (the Self Paced Training Kit):
If the object a resource refers to is changed in code, objects that use that resource behave differently, depending on how the resource is referenced. Resources referenced with the DynamicResource markup use the new object when the resource is changed in code. Objects that reference resources with the StaticResource markup continue to use the object they initially retrieved from the Resources collection and are unaware of the change.
With that said, one of the questions that they have you work through is is a XAML question. Here is the code for that question:
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<SolidColorBrush Color="Red" x:Key="ForegroundBrush" />
<SolidColorBrush Color="Blue" x:Key="BackgroundBrush" />
</Window.Resources>
<Grid>
<Button Background="{StaticResource BackgroundBrush}"
Foreground="{DynamicResource ForegroundBrush}" Height="23"
Margin="111,104,92,0" Name="Button1"
VerticalAlignment="Top">Button</Button>
</Grid>
</Window>
And the question is: What happens to the colors of the button when the following code is executed?
SolidColorBrush aBrush = new SolidColorBrush(Colors.Green);
this.Resources["ForegroundBrush"] = aBrush;
SolidColorBrush bBrush;
bBrush = (SolidColorBrush)this.Resources["BackgroundBrush"];
bBrush.Color = Colors.Black
Answer choices are:
- Nothing Happens.
- The background turns black.
- The foreground turns green.
- Both 2 and 3.
The answer given by the book is 4 Both 2 and 3.
My dilemma/confusion is: if the book states that a dynamic resource will change to reflect the changes made in code, and the static resource will continue to use the object that they initially retrieved, then why does both the background and the foreground of the button change in the code/XAML example above? And I have tried it out and they do both change.
Any help would be appreciated.