WPF 资源基础

动态资源/静态资源

UI代码

csharp 复制代码
<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>

业务代码

csharp 复制代码
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中添加

此时,界面上能够成功引用资源文件里面的样式

此时新建一个窗口,也同样能以相同的方式,使用资源字典里面的样式

在代码中,可以查找、设置 我们添加的资源

相关推荐
用户395240998804 小时前
SqlSugar 连接 PostgreSQL 报错 42P01: relation does not exist 的排查与修复
c#
2601_961875245 小时前
法考考试时间安排及科目|时间表|资料已整理
开发语言·c#·inverted-index·suffix-tree·sstable·r-tree·lsm-tree
ServBay5 小时前
你跟高级 C# 工程师的区别,就是这8个开发技巧
后端·c#·.net
2601_9618752410 小时前
法考备考计划表|学习计划|资料已整理
java·开发语言·学习·eclipse·tomcat·c#·hibernate
happyprince10 小时前
07_verl-Trainer模块详解
人工智能·架构·wpf·强化学习
Y学院11 小时前
C#游戏脚本开发全流程(Unity通用完整版)
游戏·unity·c#
淡海水13 小时前
38-Hybrid生态-LeanCLR总览
unity·架构·c#·热更新·clr·hybrid·leanclr
iCxhust13 小时前
C# 生成命令行程序 将hex格式烧录程序转换成bin烧录格式
开发语言·汇编·单片机·嵌入式硬件·c#·微机原理
bugcome_com13 小时前
WPF + Prism 技术指南与实战项目(二、模板搭建)
wpf
xiaoshuaishuai813 小时前
C# 封装与继承
开发语言·c#