WPF-使用对象资源

来源:互联网 发布:淘宝打包员累吗? 编辑:程序博客网 时间:2024/05/22 03:33

 

(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

 

原创粉丝点击