WPFの静态资源(StaticResource)和动态资源(DynamicResource)

下面是前台代码:

 <Window.Resources>
        <TextBlock x:Key="res1" Text="好好学习"/>
        <TextBlock x:Key="res2" Text="好好学习"/>
    </Window.Resources>
   
    <Grid>
        <WrapPanel Orientation="Vertical">
            <Button Content="{StaticResource res1}"/>
            <Button Content="{DynamicResource res2}"/>
            <Button Content="更新" Click="Button_Click"/>
        </WrapPanel>
    </Grid>

我们做不同的引用,动态和静态。

下面是后台代码:

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Resources["res1"] = new TextBlock { Text = "天天向上"};
            Resources["res2"] = new TextBlock { Text = "天天向上" };
        }

结果:动态资源在点击更新按钮后,更新了资源,说明静态资源只是在第一次加载窗体的时候加载,

而动态资源可以随着资源的变化时时更新。

原文地址:https://www.cnblogs.com/xietianjiao/p/6051827.html