主頁 > .NET開發 > [UWP]為番茄鐘應用設計一個平平無奇的狀態按鈕

[UWP]為番茄鐘應用設計一個平平無奇的狀態按鈕

2020-09-10 09:48:09 .NET開發

1. 為什么需要設計一個狀態按鈕

OnePomodoro應用里有個按鈕用來控制計時器的啟動/停止,本來這應該是一個包含“已啟動”和“已停止”兩種狀態的按鈕,但我以前在WPF和UWP上做過太多StateButton、ProgressButton之類的東西,已經厭倦了這種控制元件,所以我在OnePomodoro應用里只是簡單地使用兩個按鈕來實作這個功能:

<Button Content="&#xE768;"
        Visibility="{x:Bind ViewModel.IsTimerInProgress,Converter={StaticResource NegationBoolToVisibilityConverter}}"
        Command="{Binding StartTimerCommand}" />
<Button Content="&#xE769;"
        Visibility="{x:Bind  ViewModel.IsTimerInProgress,Converter={StaticResource BoolToVisibilityConverter}}"
        Command="{Binding StopTimerCommand}" />

頗有花花公子玩膩了找個良家結婚的意味,但兩個按鈕實際用起來很不順手,手感也不好,尤其狀態切換時會有種撕裂的感覺,越用越不爽,最后還是花時間又做了一個狀態按鈕PomodoroStateButton ,這個按鈕目標是要低調又炫麗,可以匹配OnePomodoro的多個主題,期間試玩了很多種技術,最后留下了這個成果:

看起來簡直就是平平無奇,

下面說說實作細節,

2. 按鈕狀態

我做自定義控制元件一定會先寫代碼部分,然后再寫XAML部分,功能和外觀要做到解耦,寫起來也不會亂,

PomodoroStateButton 繼承自Button,除了Button本身的CommonStates,PomodoroStateButton還包含以下兩組VisualState:

  • ProgressStates:Idle為番茄鐘計時器正在計時,Busy為番茄鐘停止的狀態,
  • PromodoroStates:Inwork為正處于作業狀態,Break為休息狀態,

雖然是一個放飛自我的控制元件,但基本的規則還是要遵守的,VisualState對應的TemplateVisualState不能省:

[TemplateVisualState(GroupName = ProgressStatesName, Name = IdleStateName)]
[TemplateVisualState(GroupName = ProgressStatesName, Name = BusyStateName)]
[TemplateVisualState(GroupName = PromodoroStatesName, Name = InworkStateName)]
[TemplateVisualState(GroupName = PromodoroStatesName, Name = BreakStateName)]

public class PomodoroStateButton : Button
{
    private const string ProgressStatesName = "ProgressStates";
    private const string IdleStateName = "Idle";
    private const string BusyStateName = "Busy";

    private const string PromodoroStatesName = "PromodoroStates";
    private const string InworkStateName = "Inwork";
    private const string BreakStateName = "Break";

    protected virtual void UpdateVisualStates(bool useTransitions)
    {
        VisualStateManager.GoToState(this, IsInPomodoro ? InworkStateName : BreakStateName, useTransitions);
        VisualStateManager.GoToState(this, IsTimerInProgress ? BusyStateName : IdleStateName, useTransitions);
    }

有了這些按鈕基本就滿足番茄鐘的需求了,

3. ICommand

需要支持Start和Stop兩個Command,要實作ICommand支持,控制元件中要執行如下步驟:

  • 定義Command和CommandParameter屬性,
  • 監視Command的CanExecuteChanged事件,
    *在CanExecuteChanged的事件處理函式及CommandParameter的PropertyChangedCallback中,根據Command.CanExecute(CommandParameter)的結果設定控制元件的IsEnabled屬性,
    *在某個事件(Click或者ValueChanged)中執行Command,

這篇文章里有詳細介紹:了解模板化控制元件(7):支持Command

因為從需求來說這個按鈕不需要CommandParameter,也不需要監視CanExecuteChanged事件,所以實作得簡單些:

public ICommand StartCommand
{
    get => (ICommand)GetValue(StartCommandProperty);
    set => SetValue(StartCommandProperty, value);
}

public ICommand StopCommand
{
    get => (ICommand)GetValue(StopCommandProperty);
    set => SetValue(StopCommandProperty, value);
}

private void OnClick(object sender, RoutedEventArgs e)
{
    if (IsTimerInProgress)
    {
        if (StopCommand != null && StopCommand.CanExecute(this))
            StopCommand.Execute(this);
    }
    else
    {
        if (StartCommand != null && StartCommand.CanExecute(this))
            StartCommand.Execute(this);
    }
}

4. 變形

寫完代碼部分才開始寫XAML部分,

PomodoroStateButton的ControlTempalte中最核心的是一個Polygon,在計時器啟動和停止之間按鈕圖示需要改變它的形狀,本來是三角形,需要被用戶變成正方形的形狀,這部分的操縱在ProgressStates里做,如果只是簡單地隱藏/顯示或者更換Points會很無聊,這里我使用了以前介紹過的ProgressToPointCollectionBridge,具體可以見 用Shape做影片(2) 使用與擴展PointAnimation 這篇文章,為了讓變形流暢些我讓三角形先變成圓形再變形到正方形,還加入了旋轉影片:

<VisualTransition From="Idle" To="Busy">
    <Storyboard >
        <DoubleAnimation Storyboard.TargetName="ProgressToPointCollectionBridge" Storyboard.TargetProperty="Progress" To="1" EnableDependentAnimation="True" Duration="0:0:0.3">
            <DoubleAnimation.EasingFunction>
                <CubicEase EasingMode="EaseOut"/>
            </DoubleAnimation.EasingFunction>
        </DoubleAnimation>
        <DoubleAnimation Storyboard.TargetName="ShapeCompositeTransform" Storyboard.TargetProperty="Rotation" To="180" EnableDependentAnimation="True" Duration="0:0:0.3">
            <DoubleAnimation.EasingFunction>
                <CubicEase EasingMode="EaseOut"/>
            </DoubleAnimation.EasingFunction>
        </DoubleAnimation>

    </Storyboard>
</VisualTransition>

<Border.Resources>
    <controls:ProgressToPointCollectionBridge x:Name="ProgressToPointCollectionBridge"
                   Progress="0">
        <PointCollection>三角形的點</PointCollection>
        <PointCollection>圓型的點</PointCollection>
        <PointCollection>正方形的點</PointCollection>
    </controls:ProgressToPointCollectionBridge>
</Border.Resources>

<Polygon Points="{Binding Source={StaticResource ProgressToPointCollectionBridge},Path=Points}"/>

順便提一下其它的變形方案,

HandyControl提供了GeometryAnimation,可以像使用其它線性影片那樣使用變形影片:

<hc:GeometryAnimationUsingKeyFrames Storyboard.TargetProperty="Data" Storyboard.TargetName="PathDemo">
    <hc:DiscreteGeometryKeyFrame KeyTime="0:0:0.7" Value=https://www.cnblogs.com/dino623/p/"{StaticResource FaceBookGeometry}"/>
    
        
            
        
    

也可以使用MorphSVG,或類似的SVG變形庫:

5. 傳遞AlphaMask

我在使用GetAlphaMask制作陰影這篇文章里介紹了如何使用GetAlphaMask函式獲取元素的AlphaMask,在 PomodoroStateButton里我也使用這個函式獲取了ControlTemplate中的Polygon(就是上面變形的部分)的AlphaMask,并使用這個AlphaMask創建陰影、處理MouseEnter/MouseLeave的影片、Pressed的狀態變換、還有Inwork/Break狀態切換的影片,這還真是累壞它了,而要在一個元素上處理這個多影片我也會累,所以我沒有使用DropShadowPanel那種ContentControl的方案,因為那樣只能由ContentControl自己擁有Polygon的AlphaMask,而是創建了多個ButtonDecorator控制元件,讓它們都用RelativeElement="{Binding ElementName=Shape}"的方式關聯Polygon,然后再通過GetAlphaMask函式獲取Polygon的AlphaMask,做到人手一份Polygon的AlphaMask,然后各自進行影片,這樣避免了影片太過復雜,XML大致這樣:

<controls:ButtonDecorator  x:Name="Shadow"
                           RelativeElement="{Binding ElementName=Shape}" 
                           Style="{StaticResource Shadow}"/>
<controls:ButtonDecorator RelativeElement="{Binding ElementName=Shape}"
                          x:Name="Outline"
                          Style="{StaticResource Outline}"/>
<controls:ButtonDecorator RelativeElement="{Binding ElementName=Shape}"
                          Style="{StaticResource Glow}"
                          IsInPomodoro="{TemplateBinding IsInPomodoro}"/>
<Polygon Points="{Binding Source={StaticResource ProgressToPointCollectionBridge},Path=Points}"
         StrokeThickness="4"
         Stretch="None" 
         StrokeEndLineCap="Round"
         x:Name="Shape"/>

6. 傳遞ButtonState

<VisualState x:Name="Pressed">
    <VisualState.Setters>
        <Setter Target="RootGrid.(RevealBrush.State)" Value=https://www.cnblogs.com/dino623/p/"Pressed" />
        
        
        
    

    
        
    

上面是是ButtonRevealStyle的部分XAML,應用了ButtonRevealStyle樣式的按鈕有很復雜的外觀,但它的Style寫得倒很簡潔,這是因為它把狀態傳遞給RevealBrush由它去處理影片(還有PointerDownThemeAnimation之類的),這樣分解了復雜的XAML,我也為ButtonDecorator添加了State屬性,它是一個ButtonState列舉型別的屬性:

public enum ButtonState
{
    //
    // 摘要:
    //     元素處于其默認狀態,
    Normal = 0,
    //
    // 摘要:
    //     指標在元素上,
    PointerOver = 1,
    //
    // 摘要:
    //     已按下元素,
    Pressed = 2
}

PomodoroStateButton在CommonStates的個狀態間轉變時會做輪廓的Outward和Inward影片,陰影也會變顏色,但因為通過傳遞ButtonState分離了復雜的XAML,所以CommonStates的XAML倒是寫得很簡單:

<VisualState x:Name="Normal" >
    <VisualState.Setters>
        <Setter Target="Outline.State" Value=https://www.cnblogs.com/dino623/p/"Normal"/>
        
    


    
        
        
    


    
        
        
        
    

7. 圓周影片

PomodoroStateButton在Inwork和Break之間切換的時候讓左右兩邊的藍色和紅色陰影做半圈圓周運動交換位置,雖然也可以將就些,但當時太閑了就講究起來了,

之前 介紹ProgressRing的文章 里說過怎么做圓周運動,簡單來說就是把元素放到一個大的容器里,對整個容器做旋轉,

<Page.Resources>
    <Storyboard RepeatBehavior="Forever" x:Key="Sb" >
        <DoubleAnimation Storyboard.TargetName="E1R" BeginTime="0" Storyboard.TargetProperty="Angle" Duration="0:0:4" To="360"/>
    </Storyboard>
</Page.Resources>
<Grid Background="White">
    <Canvas RenderTransformOrigin=".5,.5" Height="100" Width="100">
        <Canvas.RenderTransform>
            <RotateTransform x:Name="E1R" />
        </Canvas.RenderTransform>
        <Rectangle  Width="20"  Height="20"  Fill="MediumPurple"  />
    </Canvas>
</Grid>

但是這樣的話里面的元素也會跟著旋轉,其中一種解決方法是里面的元素用同樣的速度向著反方向做旋轉,抵消外層的旋轉,但那時我太閑用了另一種方法,也就是平移:

<Page.Resources>
    <Storyboard RepeatBehavior="Forever" x:Key="Sb" >
        <DoubleAnimationUsingKeyFrames Storyboard.TargetName="Translate1" Storyboard.TargetProperty="X" EnableDependentAnimation="True">
            <EasingDoubleKeyFrame KeyTime="0:0:4" Value=https://www.cnblogs.com/dino623/p/"120">
                
                    
                
            
            
                
                    
                
            
        

        
            
                
                    
                
            
            
                
                    
                
            
            
                
                    
                
            
            
                
                    
                
            
        
    


    
        
            
                
            
        
    

選擇QuadraticEase,搭配得宜的話可以做到漂亮的圓周運動,效果如下:

當然實際上我使用了CircleEase,效果更調皮些,PomodoroStateButton在Inwork和Break之間切換后的效果如下:

(雖然搞這么復雜也沒什么意義,)

8. 結語

這樣一個手感還不錯,看上去很收斂實際上用了一大堆代碼的狀態按鈕就完成了,使用了兩個月下來感覺手感還算好,而且很容易和各種主題的番茄鐘搭配,

可以安裝我的番茄鐘應用試玩一下,安裝地址:

一個番茄鐘

9. 原始碼

OnePomodoro_Controls at master

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/1699.html

標籤:UWP

上一篇:[UWP]使用SpringAnimation創建有趣的影片

下一篇:[UWP]使用CompositionAPI的翻轉影片

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more