[UWP]創建一個ProgressControl


1. 前言

博客園終於新增了UWP的分類,我來為這個分類貢獻第一篇博客吧。

UWP有很多問題,先不說生態的事情,表單、驗證、輸入、設計等等一堆基本問題纏身。但我覺得最應該首先解決的絕對是Blend,那個隨隨便便就崩潰、報錯、比Silverlight時代還差、不能用的Blend For Visal Studio。不過無論Blend怎么壞都不能讓我寫漂亮控件的心屈服,畢竟寫了這么多年XAML,只靠Visual Studio勉勉強強還是可以寫樣式的,這篇文章介紹的控件就幾乎全靠Visual Studio寫了全部樣式(其實VisalStudio的設計器也一直報錯)。

在之前寫的文章 創建一個進度按鈕 中我實現了一個ProgressButton,它主要有以下幾個功能:

  • 有Ready、Started、Completed、Faulted四種狀態;
  • 從Ready狀態切換到Started狀態按鈕會從方形變成圓形;
  • 在Started狀態下使用Ellipse配合StrokeDashArray顯示進度;
  • 完成后可切換到Completed狀態;
  • 出錯后可切換到Faulted狀態;

運行效果如下:

無論是實現過程還是結果都很有趣,但還是有幾個問題:

  • 沒有Paused狀態;
  • Progress限定在0到1之間,其實應該參考ProgressBar可以Minimum和Maximum;
  • 除了可以點擊這點好像和Button關系不大,所以也不應該命名為-Button;

因為以上理由決定做個新的控件。

2. 改進的結果

新控件名就叫ProgressControl---因為無奈真的想不到叫什么名字了。運行效果如下:

它有Ready、Started、Completed、Faulted和Paused五個狀態。其中Paused即暫停狀態,在Started狀態點擊控件將可進入Paused狀態,並且顯示CancelButton,這時候點擊CancelButton將回到Ready狀態;當然點擊繼續的圖標就回到Started狀態。

3. 實現

由於ProgressControl的Control Template已經十分復雜,所以將它拆分成兩個部分:

  • ProgressStateIndicator,主要用於顯示各種狀態,功能和以前的ProgressButton相似,還是直接繼承自Button;
  • CancellButton,外觀上模仿progressStateIdicator,在Paused狀態下顯示;
  • 懶得為它命名的Ellipse,用於在Started狀態下顯示進度;

ProgressControl由以上三部分組成,Ready狀態(默認狀態)下只顯示ProgressStateIndicator,點擊ProgressStateIndicator觸發EventHandler StateChanging EventHandler StateChanged 事件並轉換狀態;Started狀態下同時顯示Ellipse;Paused狀態下隱藏Ellipse並顯示CancelButton。

3.1處理代碼

和之前強調的一樣,先完成代碼部分再完成UI部分會比較高效。而且UI部分怎么呈現、怎么做動畫都是它的事,代碼部分完成后就可以甩手不管由得XAML去折騰了。

首先完成ProgressStateIndicator,繼承Button,提供一個public ProgressState State { get; set; }屬性,並在State改變時改變VisualState。它的功能僅此而已,之所以把它獨立出來是因為清楚知道它的ControlTemplate比較復雜,如果不把它獨立出來ProgressControl的ControlTemplate就復雜到沒法維護了。代碼如下:


[TemplateVisualState(GroupName = ProgressStatesGroupName, Name = ReadyStateName)]
[TemplateVisualState(GroupName = ProgressStatesGroupName, Name = StartedStateName)]
[TemplateVisualState(GroupName = ProgressStatesGroupName, Name = CompletedStateName)]
[TemplateVisualState(GroupName = ProgressStatesGroupName, Name = FaultedStateName)]
[TemplateVisualState(GroupName = ProgressStatesGroupName, Name = PausedStateName)]
public partial class ProgressStateIndicator : Button
{
    public ProgressStateIndicator()
    {
        this.DefaultStyleKey = typeof(ProgressStateIndicator);
    }

    /// <summary>
    /// 獲取或設置State的值
    /// </summary>  
    public ProgressState State
    {
        get { return (ProgressState)GetValue(StateProperty); }
        set { SetValue(StateProperty, value); }
    }

    /// <summary>
    /// 標識 State 依賴屬性。
    /// </summary>
    public static readonly DependencyProperty StateProperty =
        DependencyProperty.Register("State", typeof(ProgressState), typeof(ProgressStateIndicator), new PropertyMetadata(ProgressState.Ready, OnStateChanged));

    private static void OnStateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        ProgressStateIndicator target = obj as ProgressStateIndicator;
        ProgressState oldValue = (ProgressState)args.OldValue;
        ProgressState newValue = (ProgressState)args.NewValue;
        if (oldValue != newValue)
            target.OnStateChanged(oldValue, newValue);
    }

    protected override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        UpdateVisualStates(false);
    }

    protected virtual void OnStateChanged(ProgressState oldValue, ProgressState newValue)
    {
        UpdateVisualStates(true);
    }

    private void UpdateVisualStates(bool useTransitions)
    {
        string progressState;
        switch (State)
        {
            case ProgressState.Ready:
                progressState = ReadyStateName;
                break;
            case ProgressState.Started:
                progressState = StartedStateName;
                break;
            case ProgressState.Completed:
                progressState = CompletedStateName;
                break;
            case ProgressState.Faulted:
                progressState = FaultedStateName;
                break;
            case ProgressState.Paused:
                progressState = PausedStateName;
                break;
            default:
                progressState = ReadyStateName;
                break;
        }
        VisualStateManager.GoToState(this, progressState, useTransitions);
    }
}

代碼是很普通的模板化控件的做法,記住OnApplyTemplate()中的UpdateVisualStates(false)參數一定要是False。

接下來完成ProgressControl。ProgressControl繼承RangeBase,只是為了可以使用它的Maximum、Minimum和Value三個屬性。為了可以顯示內容模仿ContentControl實現了Content屬性,因為不是直接繼承ContentControl,所以要為控件添加[ContentProperty(Name = nameof(Content))]Attribute。模仿ContentControl的部分代碼可見 了解模板化控件(2):模仿ContentControl

ProgressCotrol也提供了public ProgressState State { get; set; }屬性,這部分和ProgressStateIndicator基本一致。

最后是兩個TemplatePart:ProgressStateIndicator和CancelButton。點擊這兩個控件觸發狀態改變的事件並改變VisualState:

protected override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    _progressStateIndicator = GetTemplateChild(ProgressStateIndicatorName) as ProgressStateIndicator;
    if (_progressStateIndicator != null)
        _progressStateIndicator.Click += OnGoToNextState;

    _cancelButton = GetTemplateChild(CancelButtonName) as Button;

    if (_cancelButton != null)
        _cancelButton.Click += OnCancel;

    UpdateVisualStates(false);
}


private void OnGoToNextState(object sender, RoutedEventArgs e)
{
    switch (State)
    {
        case ProgressState.Ready:
            ChangeStateCore(ProgressState.Started);
            break;
        case ProgressState.Started:
            ChangeStateCore(ProgressState.Paused);
            break;
        case ProgressState.Completed:
            ChangeStateCore(ProgressState.Ready);
            break;
        case ProgressState.Faulted:
            ChangeStateCore(ProgressState.Ready);
            break;
        case ProgressState.Paused:
            ChangeStateCore(ProgressState.Started);
            break;
        default:
            throw new ArgumentOutOfRangeException();
    }
}

private void OnCancel(object sender, RoutedEventArgs e)
{
    if (ChangeStateCore(ProgressState.Ready))
        Cancelled?.Invoke(this, EventArgs.Empty);
}

private bool ChangeStateCore(ProgressState newstate)
{
    var args = new ProgressStateEventArgs(State, newstate);
    OnStateChanging(args);
    StateChanging?.Invoke(this, args);
    if (args.Cancel)
        return false;

    State = newstate;
    return true;
}



至於Value屬性不需要任何處理,只是給UI提供可綁定的屬性就夠了。

3.2 處理UI

大部分UI部分用到的技術都在上一篇文章 創建一個進度按鈕 介紹過了,這次只做了一些改進。

3.2.1 ContentControlStyle

<Style TargetType="ContentControl"
       x:Key="ContentElementStyle">
    <Setter Property="Foreground"
            Value="White" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ContentControl">
                <Grid Margin="0"
                      HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                      VerticalAlignment="{TemplateBinding VerticalAlignment}">
                    <control:DropShadowPanel OffsetX="0"
                                             OffsetY="0"
                                             BlurRadius="5"
                                             ShadowOpacity="0.3"
                                             VerticalContentAlignment="Stretch"
                                             HorizontalContentAlignment="Stretch">
                        <Ellipse x:Name="CompletedRectangle"
                                 Fill="{TemplateBinding Background}" />
                    </control:DropShadowPanel>
                    <FontIcon Glyph="{TemplateBinding Content}"
                              Foreground="{TemplateBinding Foreground}"
                              FontSize="{TemplateBinding FontSize}"
                              VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              x:Name="CompletedIcon" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="ContentControl"
       x:Key="CompltedElementStyle"
       BasedOn="{StaticResource ContentElementStyle}">
    <Setter Property="Background"
            Value="LightSeaGreen" />
    <Setter Property="Content"
            Value="&#xE001;" />
</Style>


<Style TargetType="ContentControl"
       x:Key="FaultElementStyle"
       BasedOn="{StaticResource ContentElementStyle}">
    <Setter Property="Background"
            Value="MediumVioletRed" />
    <Setter Property="Content"
            Value="&#xE10A;" />
</Style>


<Style TargetType="ContentControl"
       x:Key="PausedElementStyle"
       BasedOn="{StaticResource ContentElementStyle}">
    <Setter Property="Background"
            Value="CornflowerBlue" />
    <Setter Property="Content"
            Value="&#xE768;" />
</Style>

<Style TargetType="ContentControl"
       x:Key="CancelElementStyle"
       BasedOn="{StaticResource ContentElementStyle}">
    <Setter Property="Background"
            Value="OrangeRed" />
    <Setter Property="Content"
            Value="&#xE10A;" />
</Style>

之前的ProgressButton中ControlTemplate有些復雜,這次用於Started、Completed和Faulted等狀態下顯示的元素都使用樣式並統一了它們的ContentTemplete,大大簡化了ProgressStateIndicator的ControlTemplate。

3.2.2 Animation​Set

在Started到Paused之間有一個平移的過渡,為了使位移根據元素自身的寬度決定我寫了個RelativeOffsetBehavior,里面用到了UWP Community Toolkit 的 Animation​Set

if (AssociatedObject != null)
{
    var offsetX = (float)(AssociatedObject.ActualWidth * OffsetX);
    var offsetY = (float)(AssociatedObject.ActualHeight * OffsetY);
    var animationSet = AssociatedObject.Offset(offsetX, offsetY, duration: 0, easingType: EasingType.Default);
    animationSet?.Start();
}

3.2.3 Implicit Composition Animations

由於有些動畫是重復的,例如顯示進度的Ellipse從Ready到Started及從Paused到Started都是從Collapsed變到Visible,並且Opacity從0到1。為了減輕VisualTransition的負擔,在VisualTransition中只改變Ellipse的Visibility,Opacity的動畫使用了UWP Community Toolkit 的 Implicit Composition Animations

<animations:Implicit.HideAnimations>
    <animations:ScalarAnimation Target="Opacity"
                                Duration="0:0:1"
                                To="0.0"/>
</animations:Implicit.HideAnimations>
<animations:Implicit.ShowAnimations>
    <animations:OpacityAnimation Duration="0:0:3"
                                 From="0"
                                 To="1.0" />
</animations:Implicit.ShowAnimations>

這段XML即當Ellipse的Visibility值改變時調用的動畫。

4. 結語

ProgressControl已經很復雜了,只是這個控件XAML就多達800行,還有一些Behavior配合。如果可以使用Blend的話可能可以減少一些XAML,而且精力都放在XAML上,可能還有考慮不周的地方。

除了使用UWP Community Toolkit的部分基本上移植到WPF,而UWP Community Toolkit的部分應該也可以使用其它方法代替。

5. 參考

創建一個進度按鈕
Animation​Set
Implicit Composition Animations

6. 源碼

Progress-Control-Sample


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM