WPF中静态引用资源与动态引用资源的区别

WPF中静态引用资源与动态引用资源的区别

 

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"] = "更上一层楼";
}

原文地址:https://www.cnblogs.com/lizhenlin/p/5797221.html