WPF整理-使用ResourceDictionary管理Logical Resources

本文介绍如何使用ResourceDictionary在WPF应用程序中对资源进行分类和汇总,包括创建和引用笔刷资源的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为了增加资源文件的可维护性,我们应该使用ResourceDictionary对资源进行:分类、汇总。

如何实现呢?举个例子

1.新建一个WPF Application,在Application中添加一个New Item,选择ResourceDictionary。

譬如,命名为Brushes.xaml,我们用它来存放一些笔刷。打开,我们添加一个笔刷如下:

Brushes.xaml:

复制代码
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <LinearGradientBrush EndPoint="1,0" x:Key="brush1">
        <GradientStop Color="Violet" Offset="0" />
        <GradientStop Color="Orange" Offset=".7" />
        <GradientStop Color="Brown" Offset="1" />
    </LinearGradientBrush>
</ResourceDictionary>
复制代码

2.在App.xaml中Merge则个Resource。
“Open App.xaml. We need to merge external resource dictionaries into the main
application dictionary.”

打开App.xaml,添加如下内容:

复制代码
<Application x:Class="ManagingLogicalResources.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Brushes.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
复制代码

3.这样我们就可以在页面中正常使用了。

复制代码
<Window x:Class="ManagingLogicalResources.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Ellipse Fill="{StaticResource brush1}"/>
    </Grid>
</Window>
复制代码

效果如下:

 -----------------------------------

在实际开发中更常用的做法是:直接在使用的View内部Merge。

复制代码
<Window x:Class="WPFMergedDicitonary.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Brushes.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Ellipse Fill="{StaticResource brush1}"/>
    </Grid>
</Window>
复制代码

效果同上,如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值