WPF中引用資源分為靜態引用與動態引用,兩者的區別在哪里呢?我們通過一個小的例子來理解。
點擊“Update”按鈕,第2個按鈕的文字會變成“更上一層樓”,而第1個按鈕的文字沒有變化。
原因是第1個按鈕文字用的是靜態引用資源,而第2個按鈕文字用的是動態引用資源。
前台代碼:
<Window x:Class="PersonalLearning.StaticDynamicResourceDemo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="StaticDynamicResourceDemo" Height="300" Width="300">
<Window.Resources>
<sys:String x:Key="s1">欲窮千里目</sys:String>
<sys:String x:Key="s2">欲窮千里目</sys:String>
</Window.Resources>
<Grid>
<Button Content="{StaticResource s1}" HorizontalAlignment="Left" Margin="60,32,0,0" VerticalAlignment="Top" Width="187" Height="39"/>
<Button Content="{DynamicResource s2}" HorizontalAlignment="Left" Margin="60,99,0,0" VerticalAlignment="Top" Width="187" RenderTransformOrigin="0.539,0.532" Height="39"/>
<Button Content="Update" HorizontalAlignment="Left" Margin="60,180,0,0" VerticalAlignment="Top" Width="187" Height="36" Click="Button_Click_1"/>
</Grid>
</Window>
后台代碼:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Resources["s1"] = "更上一層樓";
Resources["s2"] = "更上一層樓";
}