(1)窗口级别资源
<Button Margin="25" Height="200" Width="200" FontSize="20">
<Button.Background>
<RadialGradientBrush>
<GradientStop Color="#ffc44ec4" Offset="0" />
<GradientStop Color="#ff829ceb" Offset="1" />
<GradientStop Color="#ff793879" Offset="0.669" />
</RadialGradientBrush>
</Button.Background>
</Button>
(2){ StaticResource}标记
将上面的Background封装为资源的属性,在Background属性的Extract value to Resource(将值提取到资源)选项,将资源命名。
<Window.Resources>
<RadialGradientBrush x:Key="myBrush">
<GradientStop Color="#ffc44ec4" Offset="0" />
<GradientStop Color="#ff829ceb" Offset="1" />
<GradientStop Color="#ff793879" Offset="0.669" />
</RadialGradientBrush>
</Window.Resources>
将button的Background绑定StaticResource。
<Button Background="{StaticResource myBrush}"/>
不过这样的Resources,只能在当前的窗体中调用,不能实现跨窗体资源调用,要实现跨窗体,需要在app.xaml中定义:
<Application.Resources>
<RadialGradientBrush x:Key="myBrush">
<GradientStop Color="#ffc44ec4" Offset="0" />
<GradientStop Color="#ff829ceb" Offset="1" />
<GradientStop Color="#ff793879" Offset="0.669" />
</RadialGradientBrush>
</Application.Resources>
在button中Background属性,单击Apply Resource(应用资源),查找到myBrush。
定义资源字典
多个WPF项目复用资源,创建Resource Dictionary(WPF)文件,添加资源:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<RadialGradientBrush x:Key="myBrush">
<GradientStop Color="#ffc44ec4" Offset="0" />
<GradientStop Color="#ff829ceb" Offset="1" />
<GradientStop Color="#ff793879" Offset="0.669" />
</RadialGradientBrush>
</ResourceDictionary>
然后在App.xaml中添加:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
最后在button中Background属性,单击Apply Resource(应用资源),查找到myBrush。
本文介绍了如何在WPF中使用对象资源,包括在窗口级别定义资源、使用StaticResource标记绑定背景,以及如何实现跨窗体和项目的资源复用。详细讲解了在app.xaml中定义全局资源和创建资源字典的过程。
1439

被折叠的 条评论
为什么被折叠?



