转自:https://blog.youkuaiyun.com/sinat_34328764/article/details/72943050
在WPF中用到不规则形状的按钮的时候一般是使用下载visual studio时自带的的blend for studio。
Blend是一款方便的UI设计工具,将它与WPF结合使用,可以实现很多静态或者动态的UI效果,在这里介绍一个简单的小应用,不规则的的按钮如何创建。
首先,创建新工程,这时候的主界面是这样的:
创建不规则形状的按钮的话,首先是用右侧的钢笔工具在设计器中画出一个图形,这里使用的是一个不规则的五边形:
为了让效果显示的清楚一些,给五边形添加背景色:
接下来选中五边形之后再工具栏中选中“工具”->“构成控件”并在弹出的选择框中选择“Button”,单击“确定”
可以看见左边的变成了这样子
这个时候已经构成了一个简单的Button,可以单击“运行”观察效果,但是这样的Button很没有美感,我们希望按钮在单击的时候可以触发一些效果,就像常见的鼠标移入按钮内部时颜色有变化,这样的功能要通过触发器(Trigger)来实现,这个工作如果我们是在WPF中直接写的话是非常麻烦的,但是通过blend确很简单,完成上面一步之后可以看到左上角的面板中有“资产”,“触发器”等选项,选择“触发器”,可以看到几个事件,例如,点击“IsMouseOver=True”这个选项,此时屏幕上会有“IsMouseOver=True 触发器已打开的字样”,这个时候我们对控件所做的操作都会作为触发器的动作,比如,对此时的控件的边框颜色(Stroke),颜色(Background)进行设置并进行保存。
此时,单击“运行”,我们可以看到鼠标指针移动到按钮区域的时候颜色发生了改变。
这只是一个小例子,当然同样也可以设置IsPressed等事件。
这时候切换到“XAML”视图,可以看到创建的按钮的样式,这时候可以直接将Style标签内容复制进你的WPF程序的资源字典中进行引用了。
-
<Window x:Class="Text.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:mc=
"http://schemas.openxmlformats.org/markup-compatibility/2006"
-
xmlns:local=
"clr-namespace:Text"
-
mc:Ignorable=
"d"
-
Title=
"MainWindow"
Height=
"350"
Width=
"525">
-
<Window.Resources>
-
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
-
<Setter Property="Template">
-
<Setter.Value>
-
<ControlTemplate TargetType="{x:Type Button}">
-
<Grid>
-
<Path x:Name="path" Data="M160,80 L134.5,109.5 169.5,134.5 229.5,129.5 219.5,69.5 z" Fill="#FF5B5BC5" Stretch="Fill" Stroke="Black"/>
-
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
-
</Grid>
-
<ControlTemplate.Triggers>
-
<Trigger Property="IsFocused" Value="True"/>
-
<Trigger Property="IsDefaulted" Value="True"/>
-
<Trigger Property="IsMouseOver" Value="True">
-
<Setter Property="Fill" TargetName="path" Value="#FF43A873"/>
-
<Setter Property="Stroke" TargetName="path" Value="#FFBFD132"/>
-
<Setter Property="StrokeThickness" TargetName="path" Value="3"/>
-
</Trigger>
-
<Trigger Property="IsPressed" Value="True"/>
-
<Trigger Property="IsEnabled" Value="False"/>
-
</ControlTemplate.Triggers>
-
</ControlTemplate>
-
</Setter.Value>
-
</Setter>
-
</Style>
-
</Window.Resources>
-
<Grid>
-
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Height="66" Margin="134.5,69.5,0,0" Style="{DynamicResource ButtonStyle1}" VerticalAlignment="Top" Width="96"/>
-
<Path Data="M430,160" Fill="#FF5B5BC5" HorizontalAlignment="Right" Margin="0,160,87.6,159.4" Stretch="Fill" Stroke="Black" Width="1"/>
-
-
</Grid>
-
</Window>