(四)Style样式外部引用

一:右键添加资源字典命名为BaseButtonStyle

直接写入资源样式:

复制代码
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WpfTest">
 

    <!--设置基础的Style-->
    <Style TargetType="Button">
        <Setter Property="Background" Value="WhiteSmoke"/>
        <Setter Property="FontSize" Value="20"/>
        <Setter Property="Margin" Value="0,10,20,20"/>
    </Style>

    <!--定义特别的Style并引用继承基础的Button样式-->
    <Style x:Key="LoginStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="Background" Value="Blue"/>
    </Style>

    <!--定义特别的Style并引用继承基础的Button样式-->
    <Style x:Key="QuitStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="Background" Value="Red"/>
    </Style>

</ResourceDictionary>
复制代码

二:在App.xaml中添加全局字典引用,注意source格式路径,如果有文件夹则填入文件夹路径

复制代码
<Application x:Class="WpfTest.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfTest"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!--对Style进行全局引用-->
                <ResourceDictionary Source="/WpfTest;component/BaseButtonStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
        
    </Application.Resources>
</Application>
复制代码

三:所有Xaml窗口都可以引用此样式

复制代码
<Window x:Class="WpfTest.WindowStyle"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfTest"
        mc:Ignorable="d"
        Title="WindowStyle" Height="450" Width="800">

    <Grid>

        <StackPanel>
            <Button Style="{DynamicResource LoginStyle}"  Content="登录"/>
            <Button Style="{DynamicResource QuitStyle}"  Content="退出"/>
        </StackPanel>
       
        
    </Grid>
</Window>
复制代码

 

posted @   灰色小五  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
点击右上角即可分享
微信分享提示