WPF中的“资源”
2023-03-20 15:22:43 时间
WPF中的“资源”
资源概述
WPF中的资源的概念有点类似 web 技术中的静态资源的概念。可以是一个样式,也可以是一个button的边框设置集合。
可以简单的将资源分为如下几个类别:
- 窗体资源:顾名思义,仅可在当前窗体中使用
- 全局资源:相对于窗体资源而言,是一个全局级别的,可以被多个窗体引用,可以根据不同的维度定义多个全局资源文件
- 动态资源:“值”可以被改变的资源,例如:程序启动的时候button的边框是红色的,当点击某个其他按钮后,将边框变成蓝色
窗体资源
创建
<Window.Resources>
<SolidColorBrush x:Key="SolidColor" Color="Red">
</SolidColorBrush>
</Window.Resources>
引用
使用花括号和关键字 StaticResource
<StackPanel>
<Button Content="我是一个按钮" Margin="10" BorderBrush="{StaticResource SolidColor}"></Button>
</StackPanel>
全局资源
创建 资源字典 文件
右键工程,点击添加-资源字典,命名为 DictionaryButton.xaml
编写全局资源
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="GlobalSolidColor" Color="Yellow"></SolidColorBrush>
<Style x:Key="DefaultButtonStyle" TargetType="Button">
<Setter Property="Foreground" Value="Blue" ></Setter>
<Setter Property="FontSize" Value="20" ></Setter>
<Setter Property="BorderBrush" Value="Pink" ></Setter>
<Setter Property="BorderThickness" Value="10" ></Setter>
</Style>
</ResourceDictionary>
引入
在 App.xaml 文件中引入全局资源文件 DictionaryButton.xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="DictionaryButton.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
引用
<StackPanel>
<Button Content="我是一个按钮" Margin="10" Style="{StaticResource DefaultButtonStyle}"></Button>
</StackPanel>
动态资源
就资源本身而言,动态资源并没有什么特殊之处,仅仅是在处理方式上面的差异。
创建
参考 窗体资源
引用
<StackPanel>
<Button Content="改变下面控件的边框颜色" Margin="10" Click="Button_Click" ></Button>
<Button Content="我是一个按钮" Margin="10" BorderBrush="{DynamicResource SolidColor}" BorderThickness="10"></Button>
</StackPanel>
动态编辑资源
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Resources["SolidColor"] = new SolidColorBrush(Colors.Blue);
}
代码
https://github.com/Naylor55/WPF-Taste/tree/main/resource/ResourceTaste
相关文章
- .NET静态代码织入——肉夹馍(Rougamo) 发布1.4.0
- .NET静态代码织入——肉夹馍(Rougamo) 发布1.2.0
- ASP.NET Core - 配置系统之配置读取
- ASP.NET Core 系列总结
- ASP.NET Core - 依赖注入(四)
- 使用 dotnet-monitor 分析.NET 应用程序
- 理解ASP.NET Core - 依赖注入(Dependency Injection)
- ASP.NET Core - 依赖注入(三)
- 一次k8s docker下.net程序的异常行为dump诊断
- ASP.NET Core - 依赖注入(二)
- .NET微服务系统迁移至.NET6.0的故事
- 记一次 .NET某家装ERP系统 内存暴涨分析
- .NET依赖注入之一个接口多个实现
- IO多路复用
- ASP.NET Core中GetService()和GetRequiredService()之间的区别
- ASP.NET Core - 依赖注入(一)
- 三星为其基于 RISC-V的 Tizen平台移植.NET
- .NET周报 【2月第3期 2023-02-18】
- .NET遍历二维数组-先行/先列哪个更快?
- ASP.NET Core知识之RabbitMQ组件使用(二)