学习过程:系统自带的空间设计相对较丑,想增加一个圆弧角怎么办?简单方法如下:
<Border Height="30" Width="80" CornerRadius="2" BorderThickness="1" BorderBrush="Gray" Background="Transparent">
<Button Content="按钮3" Background="Transparent" BorderThickness="0"/>
</Border>
在Button外面,套一个Border的容器,就可以给按钮增加圆弧角,如上图按钮2所示。但如果程序中所有按钮都需要做成这样的造型呢。简单粗暴的办法就是,将所有Button外面包一个Border容器。这样做很麻烦,这时考虑用资源词典。
在项目中建一个资源词典Theme.xmal,在资源词典中重写Button的style,代码如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="border" CornerRadius="2" BorderThickness="1" BorderBrush="Gray" Background="Transparent">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualStateGroup.Transitions>
<VisualTransition GeneratedDuration="0:0:0.5" />
<VisualTransition GeneratedDuration="0" To="Pressed" />
</VisualStateGroup.Transitions>
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver"/>
<VisualState x:Name="Pressed">
<Storyboard>
<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).Color" Storyboard.TargetName="border">
<EasingColorKeyFrame KeyTime="0" Value="Gray"/>
</ColorAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.Background).Color" Storyboard.TargetName="border">
<EasingColorKeyFrame KeyTime="0" Value="DodgerBlue"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<TextBlock Text="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
资源做好了,接来是引用和绑定资源。词典和窗口不在同一个文件夹时,资源引用的写法比较特殊
1、窗口xmal文件与Theme.xaml在同级文件夹下的写法:
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--同级文件下的引用写法-->
<ResourceDictionary Source="Theme.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Button Style="{StaticResource ButtonStyle}" Height="30" Width="80" Content="按钮2"/>
</Grid>
2、窗口xmal文件与Theme.xaml不在同级文件夹下的写法:
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--不同级文件下的引用写法-->
<ResourceDictionary Source="pack://application:,,,/WpfApp1<!--项目名称-->;component/Theme.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Button Style="{StaticResource ButtonStyle}" Height="30" Width="80" Content="按钮2"/>
</Grid>
那个style看上去特复杂,其实仔细看每句话,也都能看得懂。其实看不懂,并不妨碍使用。学习编程语言就是这样的,网上的或别人的写法有太多的东西看不懂,不要紧,复制过来能用就行,后面写多了,自然就会越懂越多。不能做学院派,不要钻牛角尖,更不用知道茴香豆的“茴”字的四种写法。