WPF-使用对象资源

本文介绍了如何在WPF中使用对象资源,包括在窗口级别定义资源、使用StaticResource标记绑定背景,以及如何实现跨窗体和项目的资源复用。详细讲解了在app.xaml中定义全局资源和创建资源字典的过程。

 

(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>

将buttonBackground绑定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>

在buttonBackground属性,单击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>

最后在buttonBackground属性,单击Apply Resource(应用资源),查找到myBrush

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值