WPF全局样式、控件模板(圆角Button)和资源字典

WPF全局样式、控件模板(圆角Button)和资源字典


  1. 在解决方案中添加资源字典buttonStytle,最好自定义个文件夹放里边。如图:
    img
  2. 资源字典中写样式,注意基样式可以有key可以无key。
    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!--基类样式无key-->
    <Style TargetType="Button">
    <Setter Property="Background" Value="Yellow"/>
    </Style>
    <!--注意BaseOn写法-->
    <Style TargetType="Button" x:Key="startButton" BasedOn="{StaticResource {x:Type Button}}">
    <Setter Property="Width" Value="200"/>
    </Style>
    <!--基类样式有key-->
    <Style TargetType="Button" x:Key="quitButtonBase">
    <Setter Property="Background" Value="Blue" />
    </Style>
    <!--注意BaseOn写法-->
    <Style TargetType="Button" x:Key="quitButton" BasedOn="{StaticResource quitButtonBase}">
    <Setter Property="Width" Value="200"/>
    </Style>
    <ControlTemplate TargetType="Button" x:Key="roundButton">
    <Border Background="{TemplateBinding Background}" CornerRadius="10">
    <TextBlock Text="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    <!--这样也可以把按钮的文字属性拿过来-->
    <!--<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>-->
    </Border>
    </ControlTemplate>
``` 3. App.xaml中引用资源字典,` ` ```xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/WPFUI;component/style/buttonStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
4. 控件引用样式
```xaml
<Window
x:Class="WPFUI.MainWindow"
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:local="clr-namespace:WPFUI"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Grid>
<StackPanel>
<Button Content="开始" Style="{StaticResource startButton}" />
<Button Content="结束" Style="{StaticResource quitButton}" />
<Button
Width="100"
Height="50"
Background="#0078d4"
Content="自定义模板" FontSize="16"
Template="{StaticResource roundButton}" />
</StackPanel>
</Grid>
</Window>
  1. 结束。
posted @   张汉堡  阅读(93)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示