一、前言
在学习和工作中使用WPF时,都离不开自定义控件的使用,今天分享一个自己在学习过程中使用到的一个自定义仪表盘控件,感觉挺不错的,在这里分享给大家。(我不是大佬,我只是好代码的搬运工,具体忘了是在那里偷师拿来的)
二、功能实现
仪表控件后台逻辑其实不算复杂,相关的算法网上也有很多,主要是界面绘制这里比较重要,因为这关系到自定义控件的美观性。话不多说,开干
1、首先创建一个用户控件,然后就开始编写我们的布局文件,这里直接挂上代码来进行讲解
<UserControl x:Class="WinInfo.Control.MeterPlate"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WinInfo.Control"
mc:Ignorable="d" Background="Transparent"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Viewbox>
<Border CornerRadius="200" ClipToBounds="True"
BorderBrush="{Binding PlateBorderBrush ,RelativeSource={RelativeSource AncestorType=UserControl,Mode=FindAncestor}}"
BorderThickness="{Binding PlateBorderThickness,RelativeSource={RelativeSource AncestorType=UserControl,Mode=FindAncestor}}"
Background="{Binding PlateBackground,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}">
<Grid>
<Canvas Name="canvasPlate" Width="400" Height="400">
<Canvas.RenderTransform>
<RotateTransform Angle="-45" CenterX="200" CenterY="200"/>
</Canvas.RenderTransform>
</Canvas>
<Path Data="M100 200 A100 100 0 1 1 200 300" Stroke="#B2FFFFFF" StrokeThickness="10" StrokeStartLineCap="Round" StrokeEndLineCap="Round">
<Path.RenderTransform>
<RotateTransform Angle="-45" CenterX="200" CenterY="200"/>
</Path.RenderTransform>
</Path>
<Path Name="pointer" Data="M200 205,40 200,200 195,200 205" RenderTransformOrigin="0.5,0.5" Fill="Red">
<Path.RenderTransform>
<RotateTransform x:Name="rtPointer" Angle="-45"/>
</Path.RenderTransform>
</Path>
<Border Width="30" Height="30" CornerRadius="15">
<Border.Background>
<RadialGradientBrush>
<GradientStop Color="White" Offset="0.583"/>
<GradientStop Color="#FF97B5BD" Offset="1"/>
</RadialGradientBrush>
</Border.Background>
</Border>
</Grid>
</Border>
</Viewbox>
</Grid>
</UserControl>
a、首先是那个Border,这个是作为整个仪表盘的底图,那些背景色之类的就通过Binding关联到定义好的依赖属性那里去
b、然后就是Canvas,这个画布是用来绘制刻度值那些东西的
c、紧跟的两个Path,和那个Border是绘制仪表盘的指针和圆心的
2、接着我们转到后台逻辑的编写,这里比较复杂的就是刻度线和刻度值的绘制了,由于我不擅长讲解这些,有兴趣的可以参考大佬的博客:WPF自定义控件(1)——仪表盘设计[1]
这里就直接简单粗暴的挂出代码
public partial class MeterPlate : UserControl
{
public int Value
{
get {
return (int)GetValue(ValueProperty); }
set {
SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(int), typeof(MeterPlate),
new PropertyMetadata(default(int), new PropertyChangedCallback(OnValuePropertyChanged)));
public double Minimum
{
get {
return (double)GetValue(MinimumProperty); }
set {
SetValue(MinimumProperty, value); }
}
public