我有一個問題,讓我感到困惑。我正在學習我的MCP(測試70-511 Windows應用開發與.Net 4),我正在使用代碼中的資源和更改資源部分。這裏是直接從書報價(自進度培訓工具包):WPF 4資源
如果資源是指物體在代碼被更改,使用該資源的行爲不同,這取決於資源如何被引用的對象。在代碼中更改資源時,使用DynamicResource標記引用的資源使用新對象。使用StaticResource標記引用資源的對象繼續使用它們最初從資源中檢索到的對象,並且不知道此更改。
就這樣說,他們所要解決的問題之一就是XAML問題。下面是這個問題的代碼:
<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>
,問題是:執行下面的代碼時發生了按鈕的顏色是什麼?
SolidColorBrush aBrush = new SolidColorBrush(Colors.Green);
this.Resources["ForegroundBrush"] = aBrush;
SolidColorBrush bBrush;
bBrush = (SolidColorBrush)this.Resources["BackgroundBrush"];
bBrush.Color = Colors.Black
答案的選項:
- 沒有任何反應。
- 背景變黑。
- 前景變爲綠色。
- 均爲2和3
經書給出的答案是4或2和3
我的困境/困惑的是:如果這本書指出,動態資源將改變以反映在代碼中進行的更改以及靜態資源將繼續使用它們最初檢索的對象,那麼爲什麼上面的代碼/ XAML示例中按鈕的背景和前景都會更改?我已經嘗試過了,他們都改變了。
任何幫助,將不勝感激。