原文:
WPF教程002 - 实现Step步骤条控件
在网上看到这么一个效果,刚好在用WPF做控件,就想着用WPF来实现一下
1、实现原理
1.1、该控件分为2个模块,类似ComboBox控件分为StepBar和StepBarItem
1.2、StepBarItem定义一个Number依赖属性,用来实现每个节点上显示的步骤编号
1.3、StepBar定义一个Progress依赖属性,用来标识该控件走到了第几步,之外可以根据Progress属性与当前Item的Index来进行比较,来实现当控件进入到不同进度时,各个Item节点的样式
2、控件实现
StepBar类似ComboBox控件,但与ComboBox不同的是,由于控件本身并不需要选中,因此直接继承自ItemsControl,而不是ListBox。StepBarItem继承自ContentControl
2.1、新增StepBar、StepBarItem,分别继承自ItemsControl与ContentControl
public class StepBar : ItemsControl
{
#region Constructors
static StepBar()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(StepBar), new FrameworkPropertyMetadata(typeof(StepBar)));
}
#endregion
}
public class StepBarItem : ContentControl
{
#region Constructors
static StepBarItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(StepBarItem), new FrameworkPropertyMetadata(typeof(StepBarItem)));
}
#endregion
}
2、2、在Generic.xaml资源文件中定义这两个控件的基本样式
首先讲下大概的布局思路,StepBar比较简单,就是使用UniformGrid布局,然后设置Rows="1",这样所有的StepBarItem就会在一行显示,并且平分一行大小,否则UniformGrid默认一行是只显示2个的,重点是在StepBarItem的布局上面。
首先将文字和那根横线进行拆分,分为2列,文字那列根据内容自适应,横线则填充,因此每个StepBarItem由两部分组成:文字+横线。但是这样会有个问题,前面几个Item都会很正常的显示,但一到最后一个Item的时候,就会多出来右边的那根横线,那怎么去掉呢。我这边参照网上的思路,使用了Converter转换器,将每个Item作为参数传入转换器中,判断Item的Index与整个空间的Items.Count进行比较,如果当前的Index和Items的最后一个相等,那么久将最后一个Item的右边的那根横线给隐藏,这样就能达到文章一开始的那个效果。
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ec="http://schemas.microsoft.com/expression/2010/controls"
xmlns:ZUI="clr-namespace:ZdfFlatUI"
xmlns:Converters="clr-namespace:ZdfFlatUI.Converters">
<Converters:IsLastItemConverter x:Key="IsLastItemConverter" />
<Converters:IsProgressedConverter x:Key="IsProgressedConverter" />
<PathGeometry x:Key="Icon_Gou" Figures="M378.410667 850.450963C364.491852 850.450963 350.610963 845.293037 340.02963 834.939259L20.920889 523.529481C-0.279704 502.821926-0.279704 469.295407 20.920889 448.587852 42.121481 427.880296 76.48237 427.880296 97.682963 448.587852L378.410667 722.526815 925.75763 188.491852C946.958222 167.784296 981.319111 167.784296 1002.519704 188.491852 1023.720296 209.161481 1023.720296 242.688 1002.519704 263.395556L416.791704 834.939259C406.172444 845.293037 392.291556 850.450963 378.410667 850.450963L378.410667 850.450963Z" />
<Style TargetType="{x:Type ZUI:StepBarItem}">
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="FontSize" Value="14" />
<Setter Property="FontFamily" Value="宋体" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ZUI:StepBarItem}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<Grid Margin="0,0,10,0">
<Border x:Name="Bd" BorderBrush="#CCCCCC" Width="25" Height="25" CornerRadius="100"
BorderThickness="1" SnapsToDevicePixels="True" UseLayoutRounding="True">
</Border>
<TextBlock x:Name="Number" Text="{TemplateBinding Number}"
HorizontalAlignment="Center" VerticalAlignment="Center" />
<Path x:Name="path" Data="{StaticResource Icon_Gou}" Stretch="Uniform" Width="12" Fill="#3399FF" Visibility="Collapsed" />
</Grid>
<ContentPresenter VerticalAlignment="Center" />
</StackPanel>
<Border x:Name="Line" Grid.Column="1" BorderBrush="#E3E8EE" BorderThickness="0,1,0,0"
VerticalAlignment="Center" Margin="10,0"
SnapsToDevicePixels="True" UseLayoutRounding="True" />
</Grid>
<ControlTemplate.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource IsLastItemConverter}">
<Binding RelativeSource="{RelativeSource Self}" />
<Binding RelativeSource="{RelativeSource AncestorType={x:Type ZUI:StepBar}}" Path="Items.Count"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter TargetName="Line" Property="Visibility" Value="Collapsed" />
</DataTrigger>
<DataTrigger Value="False">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource IsLastItemConverter}">
<Binding RelativeSource="{RelativeSource Self}" />
<Binding RelativeSource="{RelativeSource AncestorType={x:Type ZUI:StepBar}}" Path="Items.Count"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter TargetName="Line" Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Value="Less">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource IsProgressedConverter}">
<Binding RelativeSource="{RelativeSource Self}" />
<Binding RelativeSource="{RelativeSource AncestorType={x:Type ZUI:StepBar}}" Path="Progress"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter TargetName="Bd" Property="Background" Value="#003399FF" />
<Setter TargetName="Bd" Property="BorderBrush" Value="#3399FF" />
<Setter TargetName="Number" Property="Visibility" Value="Collapsed" />
<Setter TargetName="Line" Property="BorderBrush" Value="#3399FF" />
<Setter TargetName="path" Property="Visibility" Value="Visible" />
<Setter Property="Foreground" Value="#999999" />
</DataTrigger>
<DataTrigger Value="Equal">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource IsProgressedConverter}">
<Binding RelativeSource="{RelativeSource Self}" />
<Binding RelativeSource="{RelativeSource AncestorType={x:Type ZUI:StepBar}}" Path="Progress"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter TargetName="Bd" Property="Background" Value="#3399FF" />
<Setter TargetName="Bd" Property="BorderBrush" Value="#3399FF" />
<Setter TargetName="Number" Property="Visibility" Value="Visible" />
<Setter TargetName="Number" Property="Foreground" Value="#FFFFFF" />
<Setter TargetName="path" Property="Visibility" Value="Collapsed" />
<Setter Property="Foreground" Value="#666666" />
</DataTrigger>
<DataTrigger Value="Large">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource IsProgressedConverter}">
<Binding RelativeSource="{RelativeSource Self}" />
<Binding RelativeSource="{RelativeSource AncestorType={x:Type ZUI:StepBar}}" Path="Progress"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Foreground" Value="#999999" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type ZUI:StepBar}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ZUI:StepBar}">
<Border>
<ItemsPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<UniformGrid IsItemsHost="True" Rows="1" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
这里有个地方需要注意一下:我在
IsLastItemConverter
转换器中同时传入了Items.Count,但是转换器中又没用到这个参数,是因为什么呢?因为在StepBar可能会在中途Add或者Remove一个Item,这样就可以动态的设置倒数第二个本来已经隐藏的横线为Visible,而不至于Add一个Item后,后面几个Item右边的横线都不显示。
2.3、新增两个转换器:IsProgressedConverter(进度转换器)和IsLastItemConverter(是否是最后一个Item)
IsProgressedConverter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace ZdfFlatUI.Converters
{
public class IsProgressedConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((values[0] is ContentControl && values[1] is int) == false)
{
return EnumCompare.None;
}
ContentControl contentControl = values[0] as ContentControl;
int progress = (int)values[1];
ItemsControl itemsControl = ItemsControl.ItemsControlFromItemContainer(contentControl);
if(itemsControl == null)
{
return EnumCompare.None;
}
int index = itemsControl.ItemContainerGenerator.IndexFromContainer(contentControl);
if(index < progress)
{
return EnumCompare.Less;
}
else if(index == progress)
{
return EnumCompare.Equal;
}
return EnumCompare.Large;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
IsLastItemConverter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace ZdfFlatUI.Converters
{
/// <summary>
/// true则隐藏,false则显示
/// </summary>
public class IsLastItemConverter : IMultiValueConverter
{
#region IValueConverter 成员
public object Convert(object[] value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
ContentControl contentPresenter = value[0] as ContentControl;
ItemsControl itemsControl = ItemsControl.ItemsControlFromItemContainer(contentPresenter);
bool flag = false;
if(itemsControl != null)
{
int index = itemsControl.ItemContainerGenerator.IndexFromContainer(contentPresenter);
flag = (index == (itemsControl.Items.Count - 1));
}
return flag;
}
public object[] ConvertBack(object value, Type[] targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
#endregion
}
}
2.4、在StepBar和StepBarItem分别新增Progress、Number依赖属性,具体的看代码,就不解释了
StepBar
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
namespace ZdfFlatUI
{
public class StepBar : ItemsControl
{
#region Private属性
#endregion
#region 依赖属性定义
public int Progress
{
get { return (int)GetValue(ProgressProperty); }
set { SetValue(ProgressProperty, value); }
}
public static readonly DependencyProperty ProgressProperty =
DependencyProperty.Register("Progress", typeof(int), typeof(StepBar), new PropertyMetadata(0, OnProgressChangedCallback, OnProgressCoerceValueCallback));
private static object OnProgressCoerceValueCallback(DependencyObject d, object baseValue)
{
//不让Progress超出边界
StepBar stepBar = d as StepBar;
int newValue = Convert.ToInt32(baseValue);
if (newValue < 0)
{
return 0;
}
else if(newValue >= stepBar.Items.Count)
{
return stepBar.Items.Count - 1;
}
return newValue;
}
private static void OnProgressChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
#endregion
#region 依赖属性set get
#endregion
#region Constructors
static StepBar()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(StepBar), new FrameworkPropertyMetadata(typeof(StepBar)));
}
#endregion
#region Override方法
protected override DependencyObject GetContainerForItemOverride()
{
return new StepBarItem();
}
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
//设置Item的显示数字
StepBarItem stepBarItem = element as StepBarItem;
ItemsControl itemsControl = ItemsControl.ItemsControlFromItemContainer(stepBarItem);
int index = itemsControl.ItemContainerGenerator.IndexFromContainer(stepBarItem);
stepBarItem.Number = Convert.ToString(++index);
base.PrepareContainerForItemOverride(element, item);
}
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
{
base.OnItemsChanged(e);
//ItemsControl数量变化时,重新设置各个Item的显示的数字
for (int i = 0; i < this.Items.Count; i++)
{
StepBarItem stepBarItem = this.ItemContainerGenerator.ContainerFromIndex(i) as StepBarItem;
if(stepBarItem != null)
{
int temp = i;
stepBarItem.Number = Convert.ToString(++temp);
}
}
//进度重新回到第一个
this.Progress = 0;
}
#endregion
#region Private方法
#endregion
}
}
StepBarItem
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
namespace ZdfFlatUI
{
public class StepBarItem : ContentControl
{
#region Private属性
#endregion
#region 依赖属性定义
public string Number
{
get { return (string)GetValue(NumberProperty); }
set { SetValue(NumberProperty, value); }
}
public static readonly DependencyProperty NumberProperty =
DependencyProperty.Register("Number", typeof(string), typeof(StepBarItem));
#endregion
#region 依赖属性set get
#endregion
#region Constructors
static StepBarItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(StepBarItem), new FrameworkPropertyMetadata(typeof(StepBarItem)));
}
#endregion
#region Override方法
#endregion
#region Private方法
#endregion
}
}
3、控件的具体使用
<StackPanel Orientation="Vertical" VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock x:Name="text" Text="{Binding ., StringFormat=当前正在进行 {0} 步}" Foreground="#957180" FontSize="14" Margin="0,0,0,20" />
<WPF.UI:StepBar x:Name="stepBar1" Width="900" Margin="0,20,0,0" />
<StackPanel Orientation="Horizontal">
<WPF.UI:FlatButton Width="70" Height="28" CornerRadius="3" Click="FlatButton_Click1" Content="Previous" Margin="10,20" />
<WPF.UI:FlatButton Width="70" Height="28" CornerRadius="3" Click="FlatButton_Click" Content="Next" Margin="10,10" />
<WPF.UI:FlatButton Width="70" Height="28" CornerRadius="3" Click="btn_AddItem" Content="Add" Margin="10,10" />
<WPF.UI:FlatButton Width="70" Height="28" CornerRadius="3" Click="btn_RemoveItem" Content="Remove" Margin="10,10" />
</StackPanel>
</StackPanel>
public partial class UCTStepBarTest : UserControl
{
private int _Step;
public int Step
{
get
{
int temp = this.stepBar.Progress;
return ++temp;
}
}
ObservableCollection<string> list = new ObservableCollection<string>();
public UCTStepBarTest()
{
InitializeComponent();
list.Add("已完成");
list.Add("进行中");
list.Add("已完成");
list.Add("进行中");
this.stepBar1.ItemsSource = list;
this.text.DataContext = Step;
}
private void FlatButton_Click(object sender, RoutedEventArgs e)
{
this.stepBar1.Progress++;
this.text.DataContext = Step;
}
private void FlatButton_Click1(object sender, RoutedEventArgs e)
{
this.stepBar1.Progress--;
this.text.DataContext = Step;
}
private void btn_AddItem(object sender, RoutedEventArgs e)
{
list.Add("进行中");
}
private void btn_RemoveItem(object sender, RoutedEventArgs e)
{
list.RemoveAt(0);
this.text.DataContext = Step;
}
}
最终的效果图如下:
最后仍然是没有达到一开始的那个效果,我设想的是文字部分应该是可以使用DataTemplate模板自定义的,但是文字详细描述那部分和横线的部分不太好布局,目前想不到该怎么去布局,思维受限了,先搁置等到后面看能不能找到合适的解决方法。