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中添加

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

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

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

相关推荐
friklogff1 小时前
【无标题】云端之C#:全面解析6种云服务提供商的SDK
开发语言·flask·c#
c#上位机2 小时前
C#事件的用法
java·javascript·c#
chnyi6_ya2 小时前
一些写leetcode的笔记
笔记·leetcode·c#
IT规划师3 小时前
C#|.net core 基础 - 扩展数组添加删除性能最好的方法
c#·.netcore·数组
时光追逐者3 小时前
分享6个.NET开源的AI和LLM相关项目框架
人工智能·microsoft·ai·c#·.net·.netcore
friklogff4 小时前
【C#生态园】提升C#开发效率:深入了解自然语言处理库与工具
开发语言·c#·区块链
__water13 小时前
『功能项目』回调函数处理死亡【54】
c#·回调函数·unity引擎
__water13 小时前
『功能项目』眩晕图标显示【52】
c#·unity引擎·动画事件
__water13 小时前
『功能项目』第二职业法师的平A【57】
c#·unity引擎·魔法球伤害传递
__water16 小时前
『功能项目』战士的伤害型技能【45】
c#·unity引擎·战士职业伤害型技能