WPF 资源基础

动态资源/静态资源

UI代码

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <!--笔刷资源-->
        <SolidColorBrush x:Key="SolidColor" Color="Red"/>
    </Window.Resources>

    <Grid>
        <StackPanel>
            <!--按钮事件,通过点击按钮,更新资源的Color-->
            <Button Content="Update" Margin="10" Click="Button_Update" />
            <!--静态绑定-->
            <Button Content="Button1" BorderBrush="{StaticResource SolidColor}" Margin="10"/>
            <!--动态绑定-->
            <Button Content="Button2" BorderBrush="{DynamicResource SolidColor}" Margin="10"/>
        </StackPanel>
    </Grid>
</Window>

业务代码

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();        
        }

        private void Button_Update(object sender, RoutedEventArgs e)
        {
            //找到资源,设置新的值
            this.Resources["SolidColor"] = new SolidColorBrush(Colors.Black);
        }
    }
}

运行结果
在这里插入图片描述
点击,Update 按钮 动态绑定的Button2边框变为黑色,Button1 未改变
在这里插入图片描述
需要控件,随着软件资源变化去改变的话,就使用DynamicResource 动态绑定

例如,软件随着Window 主题 改变颜色

资源字典

提供一个可以供所有窗口使用的,资源样式 -----资源字典

首先在项目中,添加一个资源字典
在这里插入图片描述

在这里插入图片描述

此时添加一些Button的样式

在这里插入图片描述
将资源字典的内容,添加到应用程序中
在App.xaml中添加
在这里插入图片描述

此时,界面上能够成功引用资源文件里面的样式
在这里插入图片描述
此时新建一个窗口,也同样能以相同的方式,使用资源字典里面的样式
在这里插入图片描述
在代码中,可以查找、设置 我们添加的资源

在这里插入图片描述

相关推荐

  1. WPF资源的继承

    2024-04-27 10:52:01       43 阅读
  2. WPF.NET开发】WPF中的XAML资源

    2024-04-27 10:52:01       45 阅读
  3. WPF 基础(Binding 二)

    2024-04-27 10:52:01       51 阅读
  4. WPF 基础入门 (触发器)

    2024-04-27 10:52:01       59 阅读
  5. WPF 基础入门(样式)

    2024-04-27 10:52:01       61 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-27 10:52:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-27 10:52:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-27 10:52:01       82 阅读
  4. Python语言-面向对象

    2024-04-27 10:52:01       91 阅读

热门阅读

  1. python -闭包和装饰器

    2024-04-27 10:52:01       33 阅读
  2. JVM学习

    JVM学习

    2024-04-27 10:52:01      31 阅读
  3. vulnhub——DC:7

    2024-04-27 10:52:01       27 阅读
  4. 三生随记——阴影之下

    2024-04-27 10:52:01       39 阅读
  5. 【uni-app】uni-app官方自带图标的使用方法

    2024-04-27 10:52:01       35 阅读