WPF之Style1

5.WPF之Resource Dictionary分离

在WPF中,可以新建一个项目,专门用于存放Resource Dictionary,实现设计和开发的分离。

具体步骤:

①新建一个WPF控件工程,命名为WPFResource

②删除默认新建的 usercontrol1 控件的文件

③添加ResourceDictionary文件,命名为MyWPFResource.xaml,代码为

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
        <Setter Property="Border.BorderThickness" Value="1,1,1,1" />
        <Setter Property="Border.CornerRadius" Value="3" />
        <Setter Property="Height" Value="100" />
        <Setter Property="Width" Value="100" />
        <Setter Property="Content" Value="" />
        <Setter Property="Background">
            <Setter.Value>
                <ImageBrush ImageSource="pack://siteoforigin:,,,./Images/1.png"/>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

说明:pack://siteoforigin:,,,./Images/1.png表示在当前程序的相对路径下搜索:./Images/1.png

④添加图像文件到工程下,工程结构如下图所示:图像文件属性中“复制到输出目录”选择“始终复制”,“生成操作”选择“内容”

⑤编译该工程,成功

⑥新建一个WPF应用程序,命名为WPFResourceApp

⑦在项目App.xaml中增加引用,代码如下:

<Application x:Class="WPFResourceApp.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="pack://application:,,,/WPFResource;component/MyWPFResource.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

⑧在项目中添加对项目WPFResource的引用

⑨在主窗体中添加代码,如下:该代码中指定了Button的Style为项目WPFResource中的ButtonStyle1

<Window x:Class="WPFResourceApp.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>
        <Button Style="{StaticResource ButtonStyle1}"></Button> 
    </Grid>
</Window>

⑩完成设置,运行程序,可以看到相应的效果

 

转载于:https://www.cnblogs.com/Jerrry/p/5057725.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值