wpf引用样式

在css中,可以把公用样式抽出放在一个单独的css文件里面。
在wpf中也可以做到类似的操作。

image

分离样式

把样式写在Style下的Button.xaml下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="Styles.Button" TargetType="Button">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="#ff7300"></Setter>
                <Setter Property="Foreground" Value="Red"></Setter>
            </Trigger>
        </Style.Triggers>
        <Setter Property="Width" Value="100"></Setter>
        <Setter Property="Height" Value="50"></Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

引入样式

样式可以直接在App.xaml文件中引入,也可以在需要使用的页面的<Window.Resources> 下引入

 <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Style/Button.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

控件上使用

<Button Style="{StaticResource Styles.Button}">测试</Button>

posted on   快乐海盗  阅读(236)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
历史上的今天:
2020-10-24 Vue.js 3.0搭配.NET Core写一个文件上传组件
2019-10-24 用node.js给C#写一个数据表的实体类生成工具
2019-10-24 node.js操作MySQL数据库
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示