本文主要针对WPF新手,高手可以直接忽略,更希望高手们能给出一些更好的实现思路。

前期一个小任务需要实现一个类似含步骤进度条的控件。虽然对于XAML的了解还不是足够深入,还是摸索着做了一个。这篇文章介绍下实现这个控件的步骤,最后会放出代码。还请高手们给出更好的思路。同时也希望这里的思路能给同道中人一些帮助。话不多说,开始正题。

实现中的一些代码采用了网上现有的方案,代码中通过注释标记了来源,再次对代码作者一并表示感谢。

首先放一张最终效果图。

节点可以被点击

控件会根据绑定的集合数据生成一系列节点,根据集合中的数据还可以按比例放置节点的位置。

节点的实体代码如下:

  1. public class FlowItem
  2. {
  3.     public FlowItem()
  4.     {
  5.     }
  6.  
  7.     public FlowItem(int id, string title,double offsetRate)
  8.     {
  9.         Id = id;
  10.         Title = title;
  11.         OffsetRate = offsetRate;
  12.     }
  13.  
  14.     public int Id { get; set; }
  15.  
  16.     public string Title { get; set; }
  17.  
  18.     public double OffsetRate { get; set; }
  19. }

其中三个属性分别代表了节点的编号,标题和偏移量(用来确定节点在整个条中的位置)。

控件的实现

忘了很久以前在哪看到过一句话,说设计WPF控件时不一定按照MVVM模式来设计,但一定要确保设计的控件可以按照MVVM模式来使用。本控件也是本着这么目标来完成。

控件实现为TemplatedControl,个人认为这种方式更为灵活,做出来的控件可复用度更高。反之UserControl那种组合控件的方式更适用于一个项目内复用的需要。

遵循一般的原则,我们将控件单独放于一个项目中。在TemplatedControl项目中,“模板”即XAML内容一般都放置在一个名为Generic.xaml文件中,这个文件应该放置在解决方案Themes文件夹下。

如果要使用Themes/Generic.xaml这个默认的模板样式地址,要保证AssemblyInfo.cs中如下语句:

  1. [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]

另外也不要试图修改Themes/Generic.xaml这个文件位置了。虽然据说是可以改,但不知道会不会有潜在问题。RoR流行时常说“约定大于配置”,就把这个路径当作一个约定就好了。

一般来说控件的模板也不宜直接放到Generic.xaml而是每个控件都定义到一个单独的xaml文件,然后在Generic中用如下方式进行引用。这样可以有效的防止Generic.xaml文件变的过大,也可以更利于项目模板的查找和修改(直接定位到相关文件即可,博主常用Ctrl+T键定位文件,也不知道这个是VS的功能还是Resharper的功能)。

  1. <ResourceDictionary Source="/Zq.Control;component/Flow/FlowControl.xaml"></ResourceDictionary>

这样控件的模板就可以移入FlowControl.xaml中,接着我们就看一下这里面控件模板的定义:

  1. <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  2.                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  3.                     xmlns:system="clr-namespace:System;assembly=mscorlib"
  4.                     xmlns:flow="clr-namespace:Zq.Control.Flow">
  5.  
  6.     <flow:MultiThicknessConverter x:Key="FlowMultiThicknessConverter"></flow:MultiThicknessConverter>
  7.     <flow:MultiWidthAnimationConverter x:Key="FlowMultiWidthAnimationConverter"></flow:MultiWidthAnimationConverter>
  8.     <system:Double x:Key="FlowDoubleZero">0</system:Double>
  9.     <Duration x:Key="FlowDuration">0:0:1.5</Duration>
  10.  
  11.     <Style TargetType="{x:Type flow:FlowControl}">
  12.         <Setter Property="NodeWidth" Value="30"></Setter>
  13.         <Setter Property="Template">
  14.             <Setter.Value>
  15.                 <ControlTemplate TargetType="{x:Type flow:FlowControl}">
  16.                     <Grid VerticalAlignment="Top">
  17.                         <Grid.Triggers>
  18.                             <EventTrigger RoutedEvent="SizeChanged">
  19.                                 <BeginStoryboard>
  20.                                     <Storyboard >
  21.                                         <DoubleAnimation Storyboard.TargetName="Bar" Storyboard.TargetProperty="Tag"
  22.                                              From="0" To="1" Duration="{StaticResource FlowDuration}"/>
  23.                                     </Storyboard>
  24.                                 </BeginStoryboard>
  25.                             </EventTrigger>
  26.                         </Grid.Triggers>
  27.                         <Rectangle x:Name="Bar" Panel.ZIndex="0" StrokeThickness="0" Fill="#61d0b3" 
  28.                                    HorizontalAlignment="Left" VerticalAlignment="Top"
  29.                                    Height="{TemplateBinding BarHeight}">
  30.                             <Rectangle.Margin>
  31.                                 <MultiBinding Converter="{StaticResource FlowMultiThicknessConverter}">
  32.                                     <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="BarMarginLeft"></Binding>
  33.                                     <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="BarMarginTop"></Binding>
  34.                                     <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="BarMarginLeft"></Binding>
  35.                                     <Binding Source="{StaticResource FlowDoubleZero}"></Binding>
  36.                                 </MultiBinding>
  37.                             </Rectangle.Margin>
  38.                             <Rectangle.Tag>
  39.                                 <system:Double>0.0</system:Double>
  40.                             </Rectangle.Tag>
  41.                             <Rectangle.Width>
  42.                                 <MultiBinding Converter="{StaticResource FlowMultiWidthAnimationConverter}">
  43.                                     <Binding Path="ShadowWidth" RelativeSource="{RelativeSource TemplatedParent}" />
  44.                                     <Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
  45.                                 </MultiBinding>
  46.                             </Rectangle.Width>
  47.                         </Rectangle>
  48.  
  49.                         <ItemsPresenter />
  50.                     </Grid>
  51.                 </ControlTemplate>
  52.             </Setter.Value>
  53.         </Setter>
  54.         <Setter Property="ItemsPanel">
  55.             <Setter.Value>
  56.                 <ItemsPanelTemplate>
  57.                     <flow:FlowControlPanel AnimationDuration="{StaticResource FlowDuration}" />
  58.                 </ItemsPanelTemplate>
  59.             </Setter.Value>
  60.         </Setter>
  61.     </Style>
  62.  
  63. </ResourceDictionary>

这个xaml文件的根节点是ResourceDictionary,表示其中内容是各种资源:样式,模板等等..

最开始的部分定义了模板中用到的一些Conveter及常量值。

然后就是TemplatedControl最核心的部分,Control Template的定义:

  1. <Style TargetType="{x:Type flow:FlowControl}">
  2.         <Setter Property="Template">
  3.             <Setter.Value>
  4.                 <ControlTemplate TargetType="{x:Type flow:FlowControl}">
  5.                    ...控件模板内容...
  6.                 </ControlTemplate>
  7.             </Setter.Value>
  8.         </Setter>
  9. <Style>

除了模板的定义还定义一些控件依赖属性的默认值,这些值也可以被用户显示设置的值所覆盖:

  1. <Setter Property="NodeWidth" Value="30"></Setter>

这里我们定义了节点宽度的默认值。

控件的主体分两部分,一个是背景中绿色的矩形条,另一个是节点。节点是放置在Item中,通过ItemsPresenter显示出来的。这个后面会详细说。

模板是需要配合代码使用的,正如Petzold的第一本WPF书的标题Applications = Code + Markup。我们有了“标记”了,下面来看看“代码”:

  1. public class FlowControl : ItemsControl
  2. {
  3.  
  4.     static FlowControl()
  5.     {
  6.         DefaultStyleKeyProperty.OverrideMetadata(typeof(FlowControl), new FrameworkPropertyMetadata(typeof(FlowControl)));
  7.     }
  8.  
  9.     #region dependency property
  10.  
  11.     private const double NodeWidthDefault = 30;
  12.  
  13.     public static readonly DependencyProperty NodeWidthProperty = DependencyProperty.Register(
  14.         "NodeWidth", typeof(double), typeof(FlowControl),
  15.         new PropertyMetadata(NodeWidthDefault));
  16.  
  17.     public double NodeWidth
  18.     {
  19.         get { return (double)GetValue(NodeWidthProperty); }
  20.         set
  21.         {
  22.             SetValue(NodeWidthProperty, value);
  23.         }
  24.     }
  25.  
  26.     private const double BarHeightDefault = 10;
  27.  
  28.     public static readonly DependencyProperty BarHeightProperty = DependencyProperty.Register(
  29.         "BarHeight", typeof(double), typeof(FlowControl), new PropertyMetadata(BarHeightDefault));
  30.  
  31.     public double BarHeight
  32.     {
  33.         get { return (double)GetValue(BarHeightProperty); }
  34.         set { SetValue(BarHeightProperty, value); }
  35.     }
  36.  
  37.     public static readonly DependencyProperty BarMarginLeftProperty = DependencyProperty.Register(
  38.         "BarMarginLeft", typeof(double), typeof(FlowControl), new PropertyMetadata(0.0));
  39.  
  40.     public double BarMarginLeft
  41.     {
  42.         get { return (double)GetValue(BarMarginLeftProperty); }
  43.         set { SetValue(BarMarginLeftProperty, value); }
  44.     }
  45.  
  46.     public static readonly DependencyProperty BarMarginTopProperty = DependencyProperty.Register(
  47.         "BarMarginTop", typeof(double), typeof(FlowControl), new PropertyMetadata(default(double)));
  48.  
  49.     private double BarMarginTop
  50.     {
  51.         get { return (double)GetValue(BarMarginTopProperty); }
  52.         set { SetValue(BarMarginTopProperty, value); }
  53.     }
  54.  
  55.     public static readonly DependencyProperty ShadowWidthProperty = DependencyProperty.Register(
  56.         "ShadowWidth", typeof(double), typeof(FlowControl), new PropertyMetadata(default(double)));
  57.  
  58.     private double ShadowWidth
  59.     {
  60.         get { return (double)GetValue(ShadowWidthProperty); }
  61.         set { SetValue(ShadowWidthProperty, value); }
  62.     }
  63.  
  64.     public static readonly DependencyProperty AnimationDurationProperty = DependencyProperty.Register(
  65.         "AnimationDuration", typeof(Duration), typeof(FlowControl), new PropertyMetadata(default(Duration)));
  66.  
  67.     public Duration AnimationDuration
  68.     {
  69.         get { return (Duration)GetValue(AnimationDurationProperty); }
  70.         set { SetValue(AnimationDurationProperty, value); }
  71.     }
  72.  
  73. #endregion
  74.  
  75.     protected override Size MeasureOverride(Size constraint)
  76.     {
  77.         SetValue(BarMarginLeftProperty, NodeWidth / 2);
  78.         SetValue(BarMarginTopProperty, (NodeWidth - BarHeight) / 2);
  79.         SetValue(ShadowWidthProperty, constraint.Width - BarMarginLeft * 2);
  80.  
  81.         return base.MeasureOverride(new Size(constraint.Width, NodeWidth * 3));
  82.     }
  83.  
  84.     protected override Size ArrangeOverride(Size arrangeBounds)
  85.     {
  86.         return base.ArrangeOverride(arrangeBounds);
  87.     }
  88.  
  89.     #region route event
  90.  
  91.     //route event
  92.     public static readonly RoutedEvent NodeSelectedEvent =
  93.         FlowNodeControl.NodeSelectedEvent.AddOwner(typeof(FlowControl));
  94.  
  95.     public event RoutedEventHandler NodeSelected
  96.     {
  97.         add { AddHandler(FlowNodeControl.NodeSelectedEvent, value, false); }
  98.         remove { RemoveHandler(FlowNodeControl.NodeSelectedEvent, value); }
  99.     }
  100.  
  101.     #endregion
  102.  
  103. }

可以看到这个控件由ItemsControl继承而来,像是我们节点集合这种数据很适合用ItemsControl来展示,当然我们也可以直接继承自Control自己添加处理Items的一些功能,能实现同样的效果。

大部分代码主要定义依赖属性,路由事件以及重写了父类的布局方法。构造函数中那句将代码与我们的XAML模板做了关联:

  1. DefaultStyleKeyProperty.OverrideMetadata(typeof(FlowControl), new FrameworkPropertyMetadata(typeof(FlowControl)));

这样控件的大体结构就有了。下面对其中的一些细节进行解释。

先来说说那个绿色进度条的实现,其最主要的一点就是要实现距离左上右三部分有适当的距离,而且这个距离应该随着节点小圆球半径的变化自动变化从而始终保持在节点圆球中心部位穿过。

这里的实现办法还是比较简陋的,但我没找到更好的办法:

代码中定义了2个依赖属性BarMarginLeft和BarMarginTop分别用来存储背景进度条左(右)上3部分的Margin值。这两个值是在重写的控件的布局方法MeasureOverride中根据节点的宽度进行计算得出的。

  1. protected override Size MeasureOverride(Size constraint)
  2. {
  3.     SetValue(BarMarginLeftProperty, NodeWidth / 2);
  4.     SetValue(BarMarginTopProperty, (NodeWidth - BarHeight) / 2);
  5.  
  6.     return base.MeasureOverride(new Size(constraint.Width, NodeWidth * 3));
  7. }

然后使用了一个MultiBinding和转换器(和MultiBinding配合需要实现IMultiValueConverter的多值转换器)将上面的值绑定到进度条的Margin属性:

  1. <Rectangle.Margin>
  2.     <MultiBinding Converter="{StaticResource FlowMultiThicknessConverter}">
  3.         <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="BarMarginLeft"></Binding>
  4.         <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="BarMarginTop"></Binding>
  5.         <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="BarMarginLeft"></Binding>
  6.         <Binding Source="{StaticResource FlowDoubleZero}"></Binding>
  7.     </MultiBinding>
  8. </Rectangle.Margin>

用到的多值转换器来自网上,代码如下:

  1. //来源http://stackoverflow.com/questions/6249518/binding-only-part-of-the-margin-property-of-wpf-control
  2. public class MultiThicknessConverter : IMultiValueConverter
  3. {
  4.     public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  5.     {
  6.         return new Thickness(System.Convert.ToDouble(values[0]),
  7.                              System.Convert.ToDouble(values[1]),
  8.                              System.Convert.ToDouble(values[2]),
  9.                              System.Convert.ToDouble(values[3]));
  10.     }
  11.  
  12.     public object[] ConvertBack(object value, Type[] targetType, object parameter, System.Globalization.CultureInfo culture)
  13.     {
  14.         return null;
  15.     }
  16. }

接着来看看进度条的动画(节点动画后文另说)是怎样实现的。WPF中实现动画无非就是通过Trigger触发一个BeginStoryboard,里面放一个Storyboard包装的动画。如下:

  1. <Grid.Triggers>
  2.     <EventTrigger RoutedEvent="SizeChanged">
  3.         <BeginStoryboard>
  4.             <Storyboard >
  5.                 <DoubleAnimation Storyboard.TargetName="Bar" Storyboard.TargetProperty="Tag"
  6.                      From="0" To="1" Duration="{StaticResource FlowDuration}"/>
  7.             </Storyboard>
  8.         </BeginStoryboard>
  9.     </EventTrigger>
  10. </Grid.Triggers>

我们通过EventTrigger触发动画,而这个Event就是控件Size发生变化。可能你会比较奇怪为啥动画修改的不是Width属性而是一个名为Tag的属性。

真相是由于不能将动画的To的值设置为进度条的宽度(这个From和To的值只能是一个常量值),所以在网上找到这种变通的方案(出处见下面代码的注释),动画控制一个比例值。然后进度条的Width绑定到其宽度可能的最大值*比例值。From和To设置的是这个比例的最大最小值。

这个进度条宽度的最大值通过一个名为ShadowWidth的属性来存储。其也是在控件布局时被计算:

  1. SetValue(ShadowWidthProperty, constraint.Width - BarMarginLeft * 2);

有了最大值和比例值,只需的通过一个多值绑定和转换器变为进度条的实际尺寸就可以了。

  1. <Rectangle.Width>
  2.     <MultiBinding Converter="{StaticResource FlowMultiWidthAnimationConverter}">
  3.         <Binding Path="ShadowWidth" RelativeSource="{RelativeSource TemplatedParent}" />
  4.         <Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
  5.     </MultiBinding>
  6. </Rectangle.Width>

多值转换器实现很简单,就是把传入参数相乘并返回:

  1. // stackoverflow.com/questions/2186933/wpf-animation-binding-to-the-to-attribute-of-storyboard-animation
  2. public class MultiWidthAnimationConverter : IMultiValueConverter
  3. {
  4.     public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
  5.     {
  6.         double result = 1.0;
  7.         for (int i = 0; i < values.Length; i++)
  8.         {
  9.             if (values[i] is double)
  10.                 result *= (double)values[i];
  11.         }
  12.  
  13.         return result;
  14.     }
  15.  
  16.     public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
  17.     {
  18.         throw new Exception("Not implemented");
  19.     }
  20. }

进度条基本上就这些内容了。下面看看节点的实现。

节点的布局主要通过一个自定义的Panel实现:

  1. public class FlowControlPanel : Panel
  2. {
  3.     public static readonly DependencyProperty AnimationDurationProperty = DependencyProperty.Register(
  4.         "AnimationDuration", typeof (Duration), typeof (FlowControlPanel), new PropertyMetadata(default(Duration)));
  5.  
  6.     public Duration AnimationDuration
  7.     {
  8.         get { return (Duration) GetValue(AnimationDurationProperty); }
  9.         set { SetValue(AnimationDurationProperty, value); }
  10.     }
  11.  
  12.     protected override Size MeasureOverride(Size availableSize)
  13.     {
  14.         var s = base.MeasureOverride(availableSize);
  15.         foreach (UIElement element in this.Children)
  16.         {
  17.             element.Measure(availableSize);
  18.         }
  19.         return availableSize;
  20.     }
  21.     protected override Size ArrangeOverride(Size finalSize)
  22.     {
  23.         const double y = 0;
  24.         double margin = 0;
  25.  
  26.         foreach (UIElement child in Children)
  27.         {
  28.             var newMargin = child.DesiredSize.Width / 2;
  29.             if (newMargin > margin)
  30.             {
  31.                 margin = newMargin;
  32.             }
  33.         }
  34.  
  35.         //double lastX = 0; todo
  36.         foreach (ContentPresenter element in Children)
  37.         {
  38.             var node = element.Content as FlowItem;
  39.             var x = Convert.ToDouble(node.OffsetRate) * (finalSize.Width - margin * 2);
  40.             element.Arrange(new Rect(0, y, element.DesiredSize.Width, element.DesiredSize.Height));
  41.  
  42.             //方法来自http://www.mgenware.com/blog/?p=326
  43.             var transform = element.RenderTransform as TranslateTransform;
  44.             if (transform == null)
  45.                 element.RenderTransform = transform = new TranslateTransform();
  46.  
  47.             transform.BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(0, x, AnimationDuration));
  48.  
  49.         }
  50.         return finalSize;
  51.     }
  52. }

给节点进行布局主要发生在ArrangeOverride中。取出每个节点对象中存储的OffsetRate的值乘以节点可以占据的最终宽度即节点的最终位置(x值,y值固定为0)。这个节点占据的宽度不是使用的进度条的宽度,而是用控件(面板)的最终尺寸减去一个最宽节点的宽度的一半乘二。因为节点标题的存在这个节点可分布的宽度要比进度条的宽度小。而且节点标题的宽度还不能太宽。

标题宽度通过Converter做了限制,因为进度条只能根据节点圆球的宽度进行适应,而无法根据节点实际宽度--即算上标题的宽度--进行适应,如果不限制标题长度,太长的标题会导致两头节点位置与进度条不匹配。

得到节点最终位置后,还通过一个小技巧把这个布局过程变成一个动画。动画的持续时间通过自定义模板中的依赖属性获取。传递给自定义模板的动画时间和传递给进度条动画的时间是同一个XAML常量值,这样更改持续时间时,可以很方便的让两个不同位置的动画保持一致。

通过如下的XAML将自定义Panel设置给控件的ItemsPanel属性(继承自ItemsControl控件)。

  1. <Setter Property="ItemsPanel">
  2.     <Setter.Value>
  3.         <ItemsPanelTemplate>
  4.             <flow:FlowControlPanel AnimationDuration="{StaticResource FlowDuration}" />
  5.         </ItemsPanelTemplate>
  6.     </Setter.Value>
  7. </Setter>

这样设置给控件的节点项就可以按我们希望的方式显示出来。(下面代码是调用控件的代码,我们通过MVVM方式使用控件)

  1. <flow:FlowControl HorizontalAlignment="Stretch" Margin="0 0 0 0"
  2.                       Padding="30 0" AnimationDuration="0:0:0.5"
  3.                       ItemsSource="{Binding Nodes}" >
  4.                       ...

其中Nodes的声明和初始化(ViewModel中需要完成的):

  1. private ObservableCollection<FlowItem> _nodes;
  2.  
  3. public ObservableCollection<FlowItem> Nodes
  4. {
  5.     get { return _nodes; }
  6.     set { Set(() => Nodes, ref _nodes, value); }
  7. }
  8.  
  9. _dataService.GetData(
  10.     (item, error) =>
  11.     {
  12.         Nodes = new ObservableCollection<FlowItem>(
  13.  
  14.             new List<FlowItem>()
  15.             {
  16.                 new FlowItem() {Id = 1, OffsetRate = 0, Title = "接到报修"},
  17.                 new FlowItem() {Id = 2, OffsetRate = 0.5, Title = "派工完成"},
  18.                 new FlowItem() {Id = 3, OffsetRate = 0.75, Title = "维修完成"},
  19.                 new FlowItem() {Id = 3, OffsetRate = 1, Title = "客户确认(我是特别长的标题)"},
  20.             }
  21.             );
  22.     });

可以看到从ItemsControl继承的好处就是我们立刻有了ItemsSource属性,给其赋值后就可以在Panel中访问到这些item,进行布局等操作。另外我们也得到了通过ItemTemplate设置item模板的能力,这些都无需自己另外实现:

  1. <flow:FlowControl.ItemTemplate>
  2.     <DataTemplate>
  3.         <flow:FlowNodeControl Id="{Binding Id}"
  4.             NodeTitle="{Binding Title}"
  5.             OffsetRate="{Binding OffsetRate}"></flow:FlowNodeControl>
  6.     </DataTemplate>
  7. </flow:FlowControl.ItemTemplate>

可以看到我们给Item赋的模板是另一个 TemplatedControl,这个控件用来表示一个进度节点:

这个控件模板结构很简单:

  1. <Style TargetType="flow:FlowNodeControl">
  2.     <Setter Property="NodeWidth" Value="30"></Setter>
  3.     <Setter Property="Template">
  4.         <Setter.Value>
  5.             <ControlTemplate TargetType="flow:FlowNodeControl">
  6.                 <StackPanel Orientation="Vertical">
  7.                     <RadioButton x:Name="PART_NodeRadioButton" GroupName="FlowNodeGroup" Width="{TemplateBinding NodeWidth}" Height="{TemplateBinding NodeWidth}" Style="{StaticResource FlowNodeRadioButton}"></RadioButton>
  8.                     <TextBlock Text="{TemplateBinding NodeTitle}" TextWrapping="Wrap" MaxWidth="{TemplateBinding NodeWidth,Converter={StaticResource FlowTitleMaxWidthConverter}}"></TextBlock>
  9.                 </StackPanel>
  10.             </ControlTemplate>
  11.         </Setter.Value>
  12.     </Setter>
  13. </Style>

其中就是一个RadioButton和一个TextBlock,分别用来表示绿色的节点圆圈和下面的的进度文本。另外给RadioButton定义了一套新的控件模板,用来实现进度节点被按下时的不同样式。

  1. <Style x:Key="FlowNodeRadioButton" TargetType="RadioButton">
  2.     <Setter Property="Template">
  3.         <Setter.Value>
  4.             <ControlTemplate>
  5.                 <Grid>
  6.                     <Ellipse x:Name="Border" StrokeThickness="1">
  7.                         <Ellipse.Fill>
  8.                             <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
  9.                                 <GradientStop Color="#91c885" Offset="0" />
  10.                                 <GradientStop Color="#65b254" Offset="1" />
  11.                             </LinearGradientBrush>
  12.                         </Ellipse.Fill>
  13.                     </Ellipse>
  14.                     <Ellipse x:Name="CheckMark" Margin="4" Visibility="Collapsed">
  15.                         <Ellipse.Fill>
  16.                             <SolidColorBrush Color="#20830a" />
  17.                         </Ellipse.Fill>
  18.                     </Ellipse>
  19.  
  20.                     <VisualStateManager.VisualStateGroups>
  21.                         <VisualStateGroup x:Name="CommonStates">
  22.                             <VisualState x:Name="Normal" />
  23.                             <VisualState x:Name="MouseOver">
  24.                                 <Storyboard>
  25.                                     <ColorAnimationUsingKeyFrames 
  26.                                         Storyboard.TargetName="Border" 
  27.                                         Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
  28.                                         <EasingColorKeyFrame KeyTime="0" Value="#399c24" />
  29.                                     </ColorAnimationUsingKeyFrames>
  30.                                 </Storyboard>
  31.                             </VisualState>
  32.                             <VisualState x:Name="Pressed">
  33.                                 <Storyboard>
  34.                                     <ColorAnimationUsingKeyFrames 
  35.                                         Storyboard.TargetName="Border"
  36.                                         Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
  37.                                         <EasingColorKeyFrame KeyTime="0" Value="#20830a" />
  38.                                     </ColorAnimationUsingKeyFrames>
  39.                                 </Storyboard>
  40.                             </VisualState>
  41.                             <VisualState x:Name="Disabled">
  42.                                 <Storyboard>
  43.                                     <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
  44.                                             Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[0].(GradientStop.Color)">
  45.                                         <EasingColorKeyFrame KeyTime="0" Value="#c1cbcb" />
  46.                                     </ColorAnimationUsingKeyFrames>
  47.                                     <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
  48.                                             Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
  49.                                         <EasingColorKeyFrame KeyTime="0" Value="#a0abab" />
  50.                                     </ColorAnimationUsingKeyFrames>
  51.                                 </Storyboard>
  52.                             </VisualState>
  53.                         </VisualStateGroup>
  54.                         <VisualStateGroup x:Name="CheckStates">
  55.                             <VisualState x:Name="Checked">
  56.                                 <Storyboard>
  57.                                     <ObjectAnimationUsingKeyFrames 
  58.                                         Storyboard.TargetName="CheckMark"
  59.                                         Storyboard.TargetProperty="(UIElement.Visibility)">
  60.                                         <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}" />
  61.                                     </ObjectAnimationUsingKeyFrames>
  62.                                 </Storyboard>
  63.                             </VisualState>
  64.                             <VisualState x:Name="Unchecked" />
  65.                             <VisualState x:Name="Indeterminate" />
  66.                         </VisualStateGroup>
  67.                     </VisualStateManager.VisualStateGroups>
  68.                 </Grid>
  69.             </ControlTemplate>
  70.         </Setter.Value>
  71.     </Setter>
  72. </Style>

节点控件的代码:

  1. [TemplatePart(Name = "PART_NodeRadioButton", Type = typeof(RadioButton))]
  2. public class FlowNodeControl : System.Windows.Controls.Control
  3. {
  4.     static FlowNodeControl()
  5.     {
  6.         DefaultStyleKeyProperty.OverrideMetadata(typeof(FlowNodeControl), new FrameworkPropertyMetadata(typeof(FlowNodeControl)));
  7.     }
  8.  
  9.     #region Dependency Property
  10.  
  11.     public static readonly DependencyProperty OffsetRateProperty = DependencyProperty.Register(
  12.         "OffsetRate", typeof(double), typeof(FlowNodeControl), new PropertyMetadata(default(double)));
  13.  
  14.     public double OffsetRate
  15.     {
  16.         get { return (double)GetValue(OffsetRateProperty); }
  17.         set { SetValue(OffsetRateProperty, value); }
  18.     }
  19.  
  20.     public static readonly DependencyProperty NodeTitleProperty = DependencyProperty.Register(
  21.         "NodeTitle", typeof(string), typeof(FlowNodeControl), new PropertyMetadata(string.Empty));
  22.  
  23.     public string NodeTitle
  24.     {
  25.         get { return (string)GetValue(NodeTitleProperty); }
  26.         set { SetValue(NodeTitleProperty, value); }
  27.     }
  28.  
  29.     //用于向上通知哪个Node被点击
  30.     public static readonly DependencyProperty IdProperty = DependencyProperty.Register(
  31.         "Id", typeof(int), typeof(FlowNodeControl), new PropertyMetadata(default(int)));
  32.  
  33.     public int Id
  34.     {
  35.         get { return (int)GetValue(IdProperty); }
  36.         set { SetValue(IdProperty, value); }
  37.     }
  38.  
  39.     private const double NodeWidthDefault = 30;
  40.     public static readonly DependencyProperty NodeWidthProperty = DependencyProperty.Register(
  41.         "NodeWidth", typeof(double), typeof(FlowNodeControl), new PropertyMetadata(NodeWidthDefault));
  42.  
  43.     public double NodeWidth
  44.     {
  45.         get { return (double)GetValue(NodeWidthProperty); }
  46.         set { SetValue(NodeWidthProperty, value); }
  47.     }
  48.  
  49.     #endregion
  50.  
  51.     private RadioButton nodeRadioButton;
  52.  
  53.     public override void OnApplyTemplate()
  54.     {
  55.         if (nodeRadioButton != null)
  56.         {
  57.             nodeRadioButton.Click -= nodeRadioButton_Click;
  58.         }
  59.  
  60.         base.OnApplyTemplate();
  61.  
  62.         nodeRadioButton = GetTemplateChild("PART_NodeRadioButton") as RadioButton;
  63.  
  64.         if (nodeRadioButton != null)
  65.         {
  66.             nodeRadioButton.Click += nodeRadioButton_Click;
  67.         }
  68.     }
  69.  
  70.     void nodeRadioButton_Click(object sender, RoutedEventArgs e)
  71.     {
  72.         RaiseEvent(new RoutedEventArgs(NodeSelectedEvent,this));
  73.     }
  74.  
  75.     //route event
  76.     public static readonly RoutedEvent NodeSelectedEvent = EventManager.RegisterRoutedEvent(
  77.             "NodeSelected", RoutingStrategy.Bubble,
  78.             typeof(RoutedEventHandler),
  79.             typeof(FlowNodeControl));
  80.  
  81.     public event RoutedEventHandler NodeSelected
  82.     {
  83.         add { AddHandler(NodeSelectedEvent, value); }
  84.         remove { RemoveHandler(NodeSelectedEvent, value); }
  85.     }
  86. }

其中这行:

  1. [TemplatePart(Name = "PART_NodeRadioButton", Type = typeof(RadioButton))]

说明控件模板中需要定义一个名为PART_NodeRadioButton的RadioButton,因为WPF允许控件使用者自行替换控件模板,这样的声明可以提示模板创建者模板中这个元素对于控件必不可少一定要存在。

最后一个需要介绍的功能就是点击进度节点触发控件中订阅事件的方法。

事件的来源是我们这个节点控件FlowNodeControl中的RadioButton。为了让事件可以向上传播在FlowNodeControl中定义了一个路由事件NodeSelected:

  1. //route event
  2. public static readonly RoutedEvent NodeSelectedEvent = EventManager.RegisterRoutedEvent(
  3.         "NodeSelected", RoutingStrategy.Bubble,
  4.         typeof(RoutedEventHandler),
  5.         typeof(FlowNodeControl));
  6.  
  7. public event RoutedEventHandler NodeSelected
  8. {
  9.     add { AddHandler(NodeSelectedEvent, value); }
  10.     remove { RemoveHandler(NodeSelectedEvent, value); }
  11. }

为了能在RadioButton被点击时触发这个路由事件,在代码获取RadioButton对象并手动给它关联事件处理(事件处理即触发路由事件):

  1. public override void OnApplyTemplate()
  2. {
  3.     if (nodeRadioButton != null)
  4.     {
  5.         nodeRadioButton.Click -= nodeRadioButton_Click;
  6.     }
  7.  
  8.     base.OnApplyTemplate();
  9.  
  10.     nodeRadioButton = GetTemplateChild("PART_NodeRadioButton") as RadioButton;
  11.  
  12.     if (nodeRadioButton != null)
  13.     {
  14.         nodeRadioButton.Click += nodeRadioButton_Click;
  15.     }
  16. }

如代码所示,OnApplyTemplate方法一般是获取模板中元素对应的对象的引用的地方。获取对象后给起Click事件添加处理。

接下来还需要把FlowNodeControl中的路由事件向上传递到FlowControl中,我们需要在FlowControl中定义路由事件,但不同于FlowNodeControl中,这里不是新注册一个路由事件,而是通过下面的语法告知系统FlowControl也可以处理NodeSelectedEvent事件,这样如果FlowNodeControl没有处理事件,事件将向上传播。

  1. //route event
  2. public static readonly RoutedEvent NodeSelectedEvent =
  3.     FlowNodeControl.NodeSelectedEvent.AddOwner(typeof(FlowControl));
  4.  
  5. public event RoutedEventHandler NodeSelected
  6. {
  7.     add { AddHandler(FlowNodeControl.NodeSelectedEvent, value, false); }
  8.     remove { RemoveHandler(FlowNodeControl.NodeSelectedEvent, value); }
  9. }

这样我们在使用FlowControl控件时给其NodeSelected事件绑定一个Command就可以了:

  1. <i:Interaction.Triggers>
  2.     <i:EventTrigger EventName="NodeSelected">
  3.         <command:EventToCommand Command="{Binding NodeClickCommand, Mode=OneWay}" PassEventArgsToCommand="True" />
  4.     </i:EventTrigger>
  5. </i:Interaction.Triggers>

在NodeClickCommand中可以获取被点击的节点(节点就是事件的原始触发源):

  1. private RelayCommand<RoutedEventArgs> _nodeClickCommand;
  2.  
  3. public RelayCommand<RoutedEventArgs> NodeClickCommand
  4. {
  5.     get
  6.     {
  7.         return _nodeClickCommand
  8.             ?? (_nodeClickCommand = new RelayCommand<RoutedEventArgs>(
  9.                                   p =>
  10.                                   {
  11.                                       var aa = p;
  12.                                       MessageBox.Show(((FlowNodeControl)aa.OriginalSource).NodeTitle);
  13.                                   }));
  14.     }
  15. }

基本上上面这些就把整个控件设计实现使用介绍清楚了,希望能给WPF新手以帮助,也希望WPF大神能给与更好的解决方案拓展下博主的眼界。

代码下载

Github

版权说明:本文版权归博客园和hystar所有,转载请保留本文地址。文章代码可以在项目随意使用,如果以文章出版物形式出现请表明来源,尤其对于博主引用的代码请保留其中的原出处尊重原作者劳动成果。

WPF自定义控件第一 - 进度条控件的更多相关文章

  1. Photoshop和WPF双剑配合,打造炫酷个性的进度条控件

    现在如果想打造一款专业的App,UI的设计和操作的简便性相当重要.UI设计可以借助Photoshop或者AI等设计工具,之前了解到WPF设计工具Expression Blend可以直接导入PSD文件或 ...

  2. 示例:WPF中Slider控件封装的缓冲播放进度条控件

    原文:示例:WPF中Slider控件封装的缓冲播放进度条控件 一.目的:模仿播放器播放进度条,支持缓冲任务功能 二.进度: 实现类似播放器中带缓存的播放样式(播放区域.缓冲区域.全部区域等样式) 实现 ...

  3. Qt编写自定义控件32-等待进度条控件

    一.前言 在各种各样的执行任务界面,有时候需要比较多的时间,需要给出一个直观的等待进度条表示当前正在执行的进度,而不至于懵逼在那里,用户不会觉得程序死了还是干嘛了. 等待进度条有好几种办法,比如直接叫 ...

  4. CProgressCtrl进度条控件实现进度滚动效果

    关于CProgressCtrl 控件的基本操作网上有很多资料,可我想实现进度条中进度滚动效果,即很多时候程序出现的等待或启动画面,如下图: 实现这个效果的函数为SetMarquee(_In_ BOOL ...

  5. C# 根据BackgroundWoker异步模型和ProgressBar控件,自定义进度条控件

    前言 程序开发过程中,难免会有的业务逻辑,或者算法之类产生让人能够感知的耗时操作,例如循环中对复杂逻辑处理;获取数据库百万乃至千万级数据;http请求的时候等...... 用户在使用UI操作并不知道程 ...

  6. [转载]ExtJs4 笔记(8) Ext.slider 滚轴控件、 Ext.ProgressBar 进度条控件、 Ext.Editor 编辑控件

    作者:李盼(Lipan)出处:[Lipan] (http://www.cnblogs.com/lipan/)版权声明:本文的版权归作者与博客园共有.转载时须注明本文的详细链接,否则作者将保留追究其法律 ...

  7. 用 CALayer 定制下载进度条控件

    // // RPProgressView.h // CALayer定制下载进度条控件 // // Created by RinpeChen on 16/1/2. // Copyright © 2016 ...

  8. ExtJs4 笔记(8) Ext.slider 滚轴控件、 Ext.ProgressBar 进度条控件、 Ext.Editor 编辑控件

    本篇要登场的有三个控件,分别是滚轴控件.进度条控件和编辑控件. 一.滚轴控件 Ext.slider 1.滚轴控件的定义 下面我们定义三个具有代表意义滚轴控件,分别展示滚轴横向.纵向,以及单值.多值选择 ...

  9. WPF自定义控件(一)の控件分类

    一.什么是控件(Controls) 控件是指对数据和方法的封装.控件可以有自己的属性和方法,其中属性是控件数据的简单访问者,方法则是控件的一些简单而可见的功能.控件创建过程包括设计.开发.调试(就是所 ...

随机推荐

  1. 虚拟dom与diff算法 分析

    好文集合: 深入浅出React(四):虚拟DOM Diff算法解析 全面理解虚拟DOM,实现虚拟DOM

  2. Redis数据库

    Redis是k-v型数据库的典范,设计思想及数据结构实现都值得学习. 1.数据类型 value支持五种数据类型:1.字符串(strings)2.字符串列表(lists)3.字符串集合(sets)4.有 ...

  3. 小兔JS教程(三)-- 彻底攻略JS回调函数

    这一讲来谈谈回调函数. 其实一句话就能概括这个东西: 回调函数就是把一个函数当做参数,传入另一个函数中.传进去的目的仅仅是为了在某个时刻去执行它. 如果不执行,那么你传一个函数进去干嘛呢? 就比如说对 ...

  4. C#与C++通信

    # C#与C++相互发送消息 # ## C#端: ## namespace CshapMessage { /// /// MainWindow.xaml 的交互逻辑 /// public partia ...

  5. ,net core mvc 文件上传

    工作用到文件上传的功能,在这个分享下 ~~ Controller: public class PictureController : Controller { private IHostingEnvi ...

  6. 【干货分享】流程DEMO-人员调动流程

    流程名: 调动 流程相关文件: 流程包.xml 流程说明: 直接导入流程包文件,即可使用本流程 表单:  流程:  图片:3.png DEMO包下载: http://files.cnblogs.com ...

  7. InnoDB:Lock & Transaction

    InnoDB 是一个支持事务的Engine,要保证事务ACID,必然会用到Lock.就像在Java编程一下,要保证数据的线程安全性,必然会用到Lock.了解Lock,Transaction可以帮助sq ...

  8. 初学DirectX11, 留个纪恋。

    以前学的是openGL, 最近才开始学DirectX11,写了个很垃圾的代码,怀念以前的glPushMatrix(), glPopMatrix(), glBegin(), glEnd(), 多简单啊, ...

  9. 一个无限加载瀑布流jquery实现

    实现大概是下面的效果,写了比较详细的注释 <!DOCTYPE html><html> <head> <meta charset="UTF-8&quo ...

  10. js分页页码算法

    function get_hs_page(cur_page, total_page) { var result = ""; ; i <= total_page; i++) { ...