主頁 > .NET開發 > [UWP] 模仿嗶哩嗶哩的一鍵三連

[UWP] 模仿嗶哩嗶哩的一鍵三連

2021-04-01 15:39:05 .NET開發

1. 一鍵三連

什么是一鍵三連?

嗶哩嗶哩彈幕網中用戶可以通過長按點贊鍵同時完成點贊、投幣、收藏對UP主表示支持,后UP主多用“一鍵三連”向視頻瀏覽者請求對其作品同時進行點贊、投幣、收藏,

去年在云之幻大佬的 嗶哩 專案里看到一鍵三連的 UWP 實作,覺得挺有趣的,這次參考它的代碼重新實作一次,最終成果如下:

下面這些是一鍵三連的核心功能:

  • 可以控制并顯示進度
  • 有普通狀態和完成狀態
  • 可以點擊或長按
  • 當切換到完成狀態時彈出寫泡泡
  • 點擊切換狀態
  • 長按 2 秒鐘切換狀態,期間有進度顯示

這篇文章將介紹如何使用自定義控制元件實作上面的功能,寫簡單的自定義控制元件的時候,我推薦先寫完代碼,然后再寫控制元件模板,但這個控制元件也適合一步步增加功能,所以這篇文章用逐步增加功能的方式介紹如何寫這個控制元件,

2. ProgressButton

萬事起頭難,做控制元件最難的是決定控制元件名稱,不過反正也是玩玩的 Demo,就隨便些用 ProgressButton 吧,因為有進度又可以點擊,

第二件事就是決定這個按鈕繼承自哪個控制元件,可以選擇繼承 Button 或 RangeBase 以減少需要自己實作的功能,因為長按這個需求破壞了點擊這個行為,所以還是放棄 Button 選擇 RangeBase 比較好,然后再加上 Content 屬性,控制元件的基礎代碼如下:

[ContentProperty(Name = nameof(Content))]
public partial class ProgressButton : RangeBase
{
    public ProgressButton()
    {
        DefaultStyleKey = typeof(ProgressButton);
    }

    public object Content
    {
        get => (object)GetValue(ContentProperty);
        set => SetValue(ContentProperty, value);
    }
}

在控制元件模板中用一個 CornerRadius 很大的 Border 模仿圓形邊框,ContentControl 顯示 Content,RadialProgressBar 顯示進度,控制元件模板的大致結構如下:

<ControlTemplate TargetType="local:ProgressButton">
    <Grid x:Name="RootGrid">
        <Border x:Name="RootBorder"
                        Margin="{TemplateBinding Padding}"
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="1"
                        CornerRadius="100">
            <ContentControl x:Name="ContentControl"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                    Content="{TemplateBinding Content}"
                                    Foreground="{TemplateBinding Foreground}" />
        </Border>
        <control:RadialProgressBar x:Name="PressProgressBar"
                                           Background="Transparent"
                                           Foreground="{StaticResource PrimaryColor}"
                                           Maximum="{TemplateBinding Maximum}"
                                           Minimum="{TemplateBinding Minimum}"
                                           Outline="Transparent"
                                           Value="https://www.cnblogs.com/dino623/p/{TemplateBinding Value}" />
    </Grid>
</ControlTemplate>

這時候的呼叫方式及效果如下所示:

<lab:ProgressButton x:Name="LikeButton" Content="&#xE9F0;" />
<lab:ProgressButton x:Name="CoinButton" Content="&#xEA45;" Value="https://www.cnblogs.com/dino623/p/0.5" />
<lab:ProgressButton x:Name="FavoriteButton" Content="&#xE9E5;" Value="https://www.cnblogs.com/dino623/p/1" />

3. 狀態

有了上面的代碼,后面的功能只需要按部就班地一個個添加上去,我從以前的代碼里抄來狀態相關的代碼,雖然定義了這么多狀態備用,其實我也只用到 Idle 和 Completed,其它要用到的話可以修改 ControlTemplate,

public enum ProgressState
{
    Idle,
    InProgress,
    Completed,
    Faulted,
}
  • Idle,空閑的狀態,
  • InProgress,開始的狀態,暫時不作處理,
  • Completed,完成的狀態,
  • Faulted,出錯的狀態,暫時不作處理,

在控制元件模板中添加一個粉紅色的帶一個同色陰影的圓形背景,其它狀態下隱藏,在切換到 Completed 狀態時顯示,為了好看,還添加了 ImplictAnimation 控制淡入淡出,

<ContentControl x:Name="CompletedElement"
                Template="{StaticResource CompletedTemplate}"
                Visibility="Collapsed">
    <animations:Implicit.HideAnimations>
        <animations:OpacityAnimation SetInitialValueBeforeDelay="True"
                                     From="1"
                                     To="0"
                                     Duration="0:0:0.3" />
    </animations:Implicit.HideAnimations>
    <animations:Implicit.ShowAnimations>
        <animations:OpacityAnimation SetInitialValueBeforeDelay="True"
                                     From="0"
                                     To="1"
                                     Duration="0:0:0.6" />
    </animations:Implicit.ShowAnimations>
</ContentControl>

在 VisualStateManager 中加入 ProgressStates 這組狀態,只需要控制 Completed 狀態的 Setters,顯示粉紅色的背景,隱藏邊框,文字變白色,

<VisualStateGroup x:Name="ProgressStates">
    <VisualState x:Name="Idle" />
    <VisualState x:Name="InProgress" />
    <VisualState x:Name="Completed">
        <VisualState.Setters>
            <Setter Target="RootBorder.BorderBrush" Value="https://www.cnblogs.com/dino623/p/Transparent" />
            <Setter Target="ContentControl.Foreground" Value="https://www.cnblogs.com/dino623/p/White" />
            <Setter Target="CompletedElement.Visibility" Value="https://www.cnblogs.com/dino623/p/Visible" />
        </VisualState.Setters>
    </VisualState>
    <VisualState x:Name="Faulted" />
</VisualStateGroup>

4. Button 的 CommonStates

作為一個 Button,按鈕的 PointOver 和 Pressed 狀態當然必不可少,這些邏輯我參考了 真篇文章 最后一部分代碼(不過我沒有加入 Click 事件),在控制元件模板中也制作了最簡單的處理:

<VisualStateGroup x:Name="CommonStates">
    <VisualState x:Name="PointerOver">
        <VisualState.Setters>
            <Setter Target="ContentControl.Opacity" Value="https://www.cnblogs.com/dino623/p/0.8" />
        </VisualState.Setters>
    </VisualState>
    <VisualState x:Name="Pressed">
        <VisualState.Setters>
            <Setter Target="ContentControl.Opacity" Value="https://www.cnblogs.com/dino623/p/0.6" />
        </VisualState.Setters>
    </VisualState>
</VisualStateGroup>

5. 氣泡

氣泡影片來源于火火的 BubbleButton,它封裝得很優秀,ProgressButton 只需要在 Completed 狀態下設定 BubbleView.IsBubbing = true 即可觸發氣泡影片,這大大減輕了 XAML 的作業:

<Setter Target="BubbleView.IsBubbing" Value="https://www.cnblogs.com/dino623/p/True" />

<bubblebutton:BubbleView x:Name="BubbleView"
                         HorizontalAlignment="Stretch"
                         VerticalAlignment="Stretch"
                         Foreground="{StaticResource PrimaryColor}" />

6. Tapped 和 Holding

因為要實作長按功能,所以我沒有實作 Button 的 Click,而是使用了 GestureRecognizer 的 Tapped 和 Holding,訂閱這兩個事件,觸發后重新拋出,

private GestureRecognizer _gestureRecognizer = new GestureRecognizer();

public ProgressButton()
{
    _gestureRecognizer.GestureSettings = GestureSettings.HoldWithMouse | GestureSettings.Tap | GestureSettings.Hold;
    _gestureRecognizer.Holding += OnGestureRecognizerHolding;
    _gestureRecognizer.Tapped += OnGestureRecognizerTapped;
}

public event EventHandler<HoldingEventArgs> GestureRecognizerHolding;
public event EventHandler<TappedEventArgs> GestureRecognizerTapped;

protected override void OnPointerPressed(PointerRoutedEventArgs e)
{
    // SOME CODE
    var points = e.GetIntermediatePoints(null);
    if (points != null && points.Count > 0)
    {
        _gestureRecognizer.ProcessDownEvent(points[0]);
        e.Handled = true;
    }
}

protected override void OnPointerReleased(PointerRoutedEventArgs e)
{
    // SOME CODE
    var points = e.GetIntermediatePoints(null);
    if (points != null && points.Count > 0)
    {
        _gestureRecognizer.ProcessUpEvent(points[0]);
        e.Handled = true;
        _gestureRecognizer.CompleteGesture();
    }
}

protected override void OnPointerMoved(PointerRoutedEventArgs e)
{
    // SOME CODE
    _gestureRecognizer.ProcessMoveEvents(e.GetIntermediatePoints(null));
}

private void OnGestureRecognizerTapped(GestureRecognizer sender, TappedEventArgs args)
{
    GestureRecognizerTapped?.Invoke(this, args);
}

private void OnGestureRecognizerHolding(GestureRecognizer sender, HoldingEventArgs args)
{
    GestureRecognizerHolding?.Invoke(this, args);
}

由于一鍵三連屬于業務方面的功能(要聯網、檢查狀態、還可能回退),不屬于控制元件應該提供的功能,所以 ProgressButton 只需要實作到這一步就完成了,

7. 實作一鍵三連

終于要實作一鍵三連啦,首先創建三個 ProgressButton, 然后互相雙向系結 Value 的值并訂閱事件:

<lab:ProgressButton x:Name="LikeButton"
                    Content="&#xE9F0;"
                    GestureRecognizerHolding="OnGestureRecognizerHolding"
                    GestureRecognizerTapped="OnGestureRecognizerTapped" />
<lab:ProgressButton x:Name="CoinButton"
                    Content="&#xEA45;"
                    GestureRecognizerHolding="OnGestureRecognizerHolding"
                    GestureRecognizerTapped="OnGestureRecognizerTapped"
                    Value="https://www.cnblogs.com/dino623/p/{Binding ElementName=LikeButton, Path=Value}" />
<lab:ProgressButton x:Name="FavoriteButton"
                    Content="&#xE9E5;"
                    GestureRecognizerHolding="OnGestureRecognizerHolding"
                    GestureRecognizerTapped="OnGestureRecognizerTapped"
                    Value="https://www.cnblogs.com/dino623/p/{Binding ElementName=LikeButton, Path=Value}" />

處理 Tapped 的代碼很簡單,就是反轉一下狀態:

private void OnGestureRecognizerTapped(object sender, Windows.UI.Input.TappedEventArgs e)
{
    var progressButton = sender as ProgressButton;
    if (progressButton.State == ProgressState.Idle)
        progressButton.State = ProgressState.Completed;
    else
        progressButton.State = ProgressState.Idle;
}

Holding 的代碼就復雜一些,設定一個影片的 Taget 然后啟動影片,影片完成后把所有 ProgressButton 的狀態改為 Completed,最后效果可以參考文章開頭的 gif:

private void OnGestureRecognizerHolding(object sender, Windows.UI.Input.HoldingEventArgs e)
{
    var progressButton = sender as ProgressButton;
    if (e.HoldingState == HoldingState.Started)
    {
        if (!_isAnimateBegin)
        {
            _isAnimateBegin = true;
            (_progressStoryboard.Children[0] as DoubleAnimation).From = progressButton.Minimum;
            (_progressStoryboard.Children[0] as DoubleAnimation).To = progressButton.Maximum;
            Storyboard.SetTarget(_progressStoryboard.Children[0] as DoubleAnimation, progressButton);
            _progressStoryboard.Begin();
        }
    }
    else
    {
        _isAnimateBegin = false;
        _progressStoryboard.Stop();
    }
}

private void OnProgressStoryboardCompleted(object sender, object e)
{
    LikeButton.State = ProgressState.Completed;
    CoinButton.State = ProgressState.Completed;
    FavoriteButton.State = ProgressState.Completed;
}

8. 最后

很久沒有認真寫 UWP 的博客了,我突然有了個大膽的想法,在這個時間點,會不會就算我胡說八道都不會有人認真去驗證我寫的內容?畢竟現在寫 UWP 的人又不多,不過放心,我對 UWP 是認真的,我保證我是個誠實的男人,

不過這個一鍵三連功能做出來后,又好像,完全沒機會用到嘛,難得都做出來了,就用來皮一下,

9. 原始碼

uwp_design_and_animation_lab

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

標籤:UWP

上一篇:使用 VS Code 安裝 Vue CLI一步步搭建 Vue 專案的初始環境

下一篇:C/S軟體打包部署神器InnoSetup

標籤雲
其他(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