最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

WPF自定義實現(xiàn)上傳文件顯示進度的按鈕控件

 更新時間:2023年06月12日 09:35:32   作者:BruceNeter  
自定義控件在WPF開發(fā)中是很常見的,有時候某些控件需要契合業(yè)務或者美化統(tǒng)一樣式,這時候就需要對控件做出一些改造,本文就來自定義實現(xiàn)一個上傳文件顯示進度的按鈕控件吧

話不多說直接看效果

默認效果:

上傳效果:

按鈕設置圓角

因為按鈕本身沒有CornerRadius屬性,所以只能重寫B(tài)utton的控件模板。

<Style TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border CornerRadius="5"
                            Width="{TemplateBinding Width}"
                            Background="{TemplateBinding Background}"
                            BorderThickness="1"
                            Height="{TemplateBinding Height}">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

在按鈕的模板中加入一個Border即可,但是按鈕本身沒有CornerRadius屬性,就沒辦法使用TemplateBinding ,只能寫死在樣式,那肯定不行,所以我們就需要拓展一下Button按鈕。

1.創(chuàng)建一個類MyProgressButton繼承Button類,由于是新創(chuàng)建的一個類,所以我們可以直接使用依賴屬性來完成這件事,在MyProgressButton中定義一個圓角弧度的依賴屬性。

public CornerRadius CornerRadius
        {
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
            set { SetValue(CornerRadiusProperty, value); }
        }
        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register(nameof(CornerRadius), typeof(CornerRadius), typeof(MyProgressButton), new PropertyMetadata(default));

2.創(chuàng)建一個ProgressButtonStyle.xaml的資源文件,針對MyProgressButton定義一些樣式,包括弧度的綁定和鼠標移入移出的陰影效果,讓我們的按鈕立體起來

<Style TargetType="local:MyProgressButton">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:MyProgressButton">
                    <Border CornerRadius="{TemplateBinding CornerRadius}"
                            Width="{TemplateBinding Width}"
                            Background="{TemplateBinding Background}"
                            BorderThickness="1"
                            Height="{TemplateBinding Height}">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="False">
                <Setter Property="Effect">
                    <Setter.Value>
                        <DropShadowEffect Color="#cccccc" Direction="270" ShadowDepth="2" Opacity="1" />
                    </Setter.Value>
                </Setter>
            </Trigger>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Effect" >
                    <Setter.Value>
                        <DropShadowEffect Color="#bbbbbb" Direction="270" ShadowDepth="2" Opacity="1" />
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>

3.最后在主界面將MyProgressButton的命名控件加入進來,并且用xaml創(chuàng)建一個MyProgressButton按鈕,自定義一些屬性,并且將ProgressButtonStyle.xaml樣式加入到App.xaml中

<Window x:Class="ProgressButton.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ProgressButton"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:MyProgressButton Content="上傳文件" 
                                Foreground="#555555"
                                Cursor="Hand"
                                FontSize="14"
                                CornerRadius="5"
                                HorizontalAlignment="Center"
                                VerticalAlignment="Center"
                                Height="40" Width="135" 
                                Background="Salmon"
                                x:Name="upload_btn">
        </local:MyProgressButton>
    </Grid>
</Window>
<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/ProgressButton;component/Button/ProgressButtonStyle.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

看看效果:

按鈕上傳文件相關定義

1.定義按鈕類型MyProgressButton文件上傳進度,是否上傳,以及上傳時按鈕背景色三個依賴屬性

/// <summary>
        /// 文件上傳進度
        /// </summary>
        public double Progress
        {
            get { return (double)GetValue(ProgressProperty); }
            set { SetValue(ProgressProperty, value); }
        }
        public static readonly DependencyProperty ProgressProperty =
            DependencyProperty.Register(nameof(Progress), typeof(double), typeof(MyProgressButton), new PropertyMetadata(double.NegativeZero, OnProgressChanged));
        /// <summary>
        /// 文件是否上傳
        /// </summary>
        public bool IsUploading
        {
            get { return (bool)GetValue(IsUploadingProperty); }
            set { SetValue(IsUploadingProperty, value); }
        }
        public static readonly DependencyProperty IsUploadingProperty =
            DependencyProperty.Register(nameof(IsUploading), typeof(bool), typeof(MyProgressButton), new PropertyMetadata(false, OnIsUploadingChanged));
        /// <summary>
        /// 上傳時按鈕背景色
        /// </summary>
        public Color UploadingColor
        {
            get { return (Color)GetValue(UploadingColorProperty); }
            set { SetValue(UploadingColorProperty, value); }
        }
        // Using a DependencyProperty as the backing store for UploadingColor.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty UploadingColorProperty =
            DependencyProperty.Register(nameof(UploadingColor), typeof(Color), typeof(MyProgressButton), new PropertyMetadata(Colors.White));

2.如何實現(xiàn)按鈕內(nèi)部的進度顯示?有幾種辦法,比如使用漸進色修改偏移,或者按鈕內(nèi)部套一個進度條,或者按鈕內(nèi)部放兩個不同顏色的塊控件,動態(tài)修改兩者的長度。我們選擇第一種。

在Progress屬性被修改的時候,我們動態(tài)修改下按鈕內(nèi)部漸進色的偏移。為ProgressProperty添加值變化的回調(diào)。

private static void OnProgressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var btn = d as MyProgressButton;
            var progress = (double)e.NewValue;
            if (progress != double.NegativeZero)
            {
                Brush brush = null;
                if ((brush = btn.Background as LinearGradientBrush) != null) //如果按鈕本身是線性漸變色則直接修改偏移
                {
                    GradientStopCollection collections =
                        brush.GetValue(GradientBrush.GradientStopsProperty) as GradientStopCollection;
                    collections[1].Offset = collections[0].Offset = progress / 100;
                }
                else //如果本身不是線性漸變色則將背景色修改為線性漸變色
                {
                    LinearGradientBrush linearGradientBrush = new LinearGradientBrush();
                    //設置一個橫向的線
                    linearGradientBrush.StartPoint = new Point(0, 0.5);
                    linearGradientBrush.EndPoint = new Point(1, 0.5);
                    GradientStop gradientStop = new GradientStop(); //右邊的顏色,即按鈕設置的上傳時背景色
                    gradientStop.Color = btn!.UploadingColor;
                    GradientStop gradientStop1 = new GradientStop();//左邊的顏色,即按鈕原本的顏色
                    gradientStop1.Color = (btn!.Background as SolidColorBrush)!.Color;
                    gradientStop.Offset = gradientStop1.Offset = progress / 100;
                    linearGradientBrush.GradientStops.Add(gradientStop1);
                    linearGradientBrush.GradientStops.Add(gradientStop);
                    btn.Background = linearGradientBrush;
                }
            }
        }

在上傳文件的時候,將按鈕置為禁用,防止重復點擊。寫一個IsUploadingProperty屬性的值變化的回調(diào)。

private static void OnIsUploadingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var btn = d as MyProgressButton;
            if ((bool)e.NewValue)
            {
                btn!.IsEnabled = false;
            }
            else
            {
                btn!.IsEnabled = true;
            }
        }

測試代碼

Binding binding = new Binding();
            binding.Source = this;
            binding.Path = new PropertyPath("Progress");
            binding.Mode = BindingMode.OneWay;
            upload_btn.SetBinding(MyProgressButton.ProgressProperty, binding);
            Binding binding1 = new Binding();
            binding1.Source = this;
            binding1.Path = new PropertyPath("IsUploading");
            binding1.Mode = BindingMode.OneWay;
            upload_btn.SetBinding(MyProgressButton.IsUploadingProperty, binding1);
private async void upload_btn_Click(object sender, RoutedEventArgs e)
        {
            IsUploading = true;
            try
            {
                using (FileStream fread = new FileStream("d://d3dcompiler_47.dll", FileMode.Open, FileAccess.Read))
                using (FileStream fwrite = new FileStream("d://d3dcompiler_47_copy.dll", FileMode.OpenOrCreate, FileAccess.Write))
                {
                    var allLength = new FileInfo("d://d3dcompiler_47.dll").Length;
                    long copyedBytes = 0;
                    while (true)
                    {
                        var buffer = ArrayPool<byte>.Shared.Rent(1024 * 10);
                        try
                        {
                            var len = await fread.ReadAsync(buffer, 0, buffer.Length);
                            if (len > 0)
                            {
                                await fwrite.WriteAsync(buffer[..len]);
                                copyedBytes += len;
                                Progress = copyedBytes * 100 / allLength;
                                await Task.Delay(20);
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch { break; }
                        finally
                        {
                            ArrayPool<byte>.Shared.Return(buffer);
                        }
                    }
                    MessageBox.Show("上傳成功");
                };
            }
            finally
            {
                IsUploading = false;
            }
        }

到此這篇關于WPF自定義實現(xiàn)上傳文件顯示進度的按鈕控件的文章就介紹到這了,更多相關WPF自定義控件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • C# SQLite 高級功能詳解(推薦)

    C# SQLite 高級功能詳解(推薦)

    本文介紹C#中SQLite的高級應用,涵蓋事務處理(ACID)、連接池、批量操作、異步編程及性能優(yōu)化,強調(diào)數(shù)據(jù)安全與并發(fā)控制,適用于移動和桌面開發(fā),感興趣的朋友跟隨小編一起看看吧
    2025-06-06
  • Unity中EventTrigger的幾種使用操作

    Unity中EventTrigger的幾種使用操作

    這篇文章主要介紹了Unity中EventTrigger的幾種使用操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-04-04
  • 解析C#中@符號的幾種使用方法詳解

    解析C#中@符號的幾種使用方法詳解

    本篇文章是對C#中@符號的幾種使用方法進行了詳細的分析介紹,需要的朋友參考下
    2013-05-05
  • C#實現(xiàn)將Doc文檔轉換成rtf格式的方法示例

    C#實現(xiàn)將Doc文檔轉換成rtf格式的方法示例

    這篇文章主要介紹了C#實現(xiàn)將Doc文檔轉換成rtf格式的方法,結合實例形式分析了C#針對word文件的讀取及文檔格式轉換相關操作技巧,需要的朋友可以參考下
    2017-07-07
  • C#實現(xiàn)在控制臺輸入密碼顯示星號的方法

    C#實現(xiàn)在控制臺輸入密碼顯示星號的方法

    這篇文章主要介紹了C#實現(xiàn)在控制臺輸入密碼顯示星號的方法,感興趣的小伙伴們可以參考一下
    2016-04-04
  • C#比較兩個List集合內(nèi)容是否相同的幾種方法

    C#比較兩個List集合內(nèi)容是否相同的幾種方法

    本文詳細介紹了在C#中比較兩個List集合內(nèi)容是否相同的方法,包括非自定義類和自定義類的元素比較,對于非自定義類,可以使用SequenceEqual、排序后比較或HashSet來忽略重復元素,對于自定義類,需要重寫Equals和GetHashCode方法,然后使用相應的比較方法
    2025-02-02
  • 解讀赫夫曼樹編碼的問題

    解讀赫夫曼樹編碼的問題

    本篇文章對赫夫曼樹編碼的問題進行了分析說明,需要的朋友參考下
    2013-05-05
  • Unity實現(xiàn)QQ列表折疊菜單

    Unity實現(xiàn)QQ列表折疊菜單

    這篇文章主要為大家詳細介紹了Unity實現(xiàn)QQ列表折疊菜單,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • 如何在C#項目中鏈接一個文件夾下的所有文件詳解

    如何在C#項目中鏈接一個文件夾下的所有文件詳解

    很多時候我們需要獲取一個結構未知的文件夾下所有的文件或是指定類型的所有文件,下面這篇文章主要給大家介紹了關于如何在C#項目中鏈接一個文件夾下的所有文件,需要的朋友可以參考下
    2023-02-02
  • c#如何使用 XML 文檔功能

    c#如何使用 XML 文檔功能

    這篇文章主要介紹了c#如何使用 XML 文檔功能,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下
    2020-10-10

最新評論

阜城县| 阜南县| 临清市| 介休市| 田阳县| 乳源| 托克逊县| 温宿县| 尉氏县| 麦盖提县| 上虞市| 堆龙德庆县| 富蕴县| 霞浦县| 商南县| 永安市| 通辽市| 阆中市| 玉环县| 积石山| 汨罗市| 青冈县| 赤峰市| 浮山县| 喀喇沁旗| 永登县| 铜鼓县| 安康市| 太白县| 紫云| 莒南县| 天等县| 巫山县| 百色市| 久治县| 清水河县| 大洼县| 大同县| 简阳市| 英山县| 鄂伦春自治旗|