[WPF]StaticResource VS DynamicResource
WPF常見的參考資源的宣告有StaticResource與DynamicResource, 使用方式如下,
XAML如下,
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Window.Resources>
<SolidColorBrush Color="Red" x:Key="ForegroundBrush" />
<SolidColorBrush Color="Blue" x:Key="BackgroundBrush" />
<SolidColorBrush Color="Gray" x:Key="GridBackgroundBrush" />
<SolidColorBrush Color="Yellow" x:Key="Btn2BackgroundBrush" />
</Window.Resources>
<Grid Background="{StaticResource GridBackgroundBrush}">
<Button Background="{StaticResource BackgroundBrush}"
Foreground="{StaticResource ForegroundBrush}" Height="23" Margin="111,104,92,0" Name="Button1"
VerticalAlignment="Top">Button1</Button>
<Button Background="{DynamicResource Btn2BackgroundBrush}" Height="23">Button2 </Button>
</Grid>
</Window>
CS如下,
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//直接換掉Resource,而Grid是使用StaticResource,所以不會更換
this.Resources["GridBackgroundBrush"] = new SolidColorBrush(Colors.Chocolate);
//直接換掉Resource,而Button2是使用DynamicResource,所以會更換
this.Resources["Btn2BackgroundBrush"] = new SolidColorBrush(Colors.Navy);
//換掉Resource的Color,會通知Button一併更換
((SolidColorBrush)this.Resources["ForegroundBrush"]).Color = Colors.Green;
SolidColorBrush bBrush;
bBrush = (SolidColorBrush)this.Resources["BackgroundBrush"];
//換掉Resource的Color,會通知Button一併更換
bBrush.Color = Colors.Black;
}
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^