WPF全局样式、控件模板(圆角Button)和资源字典
WPF全局样式、控件模板(圆角Button)和资源字典
- 在解决方案中添加资源字典
buttonStytle
,最好自定义个文件夹放里边。如图:
- 资源字典中写样式,注意基样式可以有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>
<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>
- 结束。