91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

WPF如何實現在控件上顯示Loading等待動畫

發布時間:2023-03-25 15:54:15 來源:億速云 閱讀:190 作者:iii 欄目:開發技術

這篇文章主要介紹了WPF如何實現在控件上顯示Loading等待動畫的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇WPF如何實現在控件上顯示Loading等待動畫文章都會有所收獲,下面我們一起來看看吧。

WPF 如何在控件上顯示 Loading 等待動畫

  • 框架使用.NET40

  • Visual Studio 2022;

  • 使用方式需引入命名空間后設置控件的附加屬性 wd:Loading.IsShow="true",即可顯示默認等待動畫效果如下:

WPF如何實現在控件上顯示Loading等待動畫

  • 如需自定義 Loading 一定要 先設置 wd:Loading.Child 在設置 IsShow="true" 。

  • 顯示不同 Loading 內容需 wd:Loading.Child ={x:Static wd:NormalLoading.Default} 進行復賦值顯示 NormalLoading 效果如下:

Github[2]

Github xaml[3]

Gitee[4]

Gitee xaml[5]

WPF如何實現在控件上顯示Loading等待動畫

實現代碼

也可以自定義 Loading 動畫如下:

1、自定義控件 CustomLoading 。

public class CustomLoading : Control
    {
        public static CustomLoading Default = new CustomLoading();
        static CustomLoading()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomLoading),
                new FrameworkPropertyMetadata(typeof(CustomLoading)));
        }
    }

2、編寫 CustomLoading.xaml 代碼如下。

<Style TargetType="{x:Type controls:CustomLoading}">
        <Setter Property="Width" Value="40" />
        <Setter Property="Height" Value="40" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type controls:CustomLoading}">
                   <!--此處編寫自定義的動畫邏輯-->
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

1)創建裝飾 AdornerContainer 代碼如下:

using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

namespace WPFDevelopers.Utilities
{
    public class AdornerContainer : Adorner
    {
        private UIElement _child;
        public AdornerContainer(UIElement adornedElement) : base(adornedElement)
        {
        }
        public UIElement Child
        {
            get => _child;
            set
            {
                if (value == null)
                {
                    RemoveVisualChild(_child);
                    _child = value;
                    return;
                }
                AddVisualChild(value);
                _child = value;
            }
        }
        protected override int VisualChildrenCount
        {
            get
            {
                return _child != null ? 1 : 0;
            }
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            _child?.Arrange(new Rect(finalSize));
            return finalSize;
        }

        protected override Visual GetVisualChild(int index)
        {
            if (index == 0 && _child != null) return _child;
            return base.GetVisualChild(index);
        }
    }
}

2)創建蒙板控件 MaskControl 代碼如下:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPFDevelopers.Controls
{
    public class MaskControl : ContentControl
    {
        private readonly Visual visual;
        public static readonly DependencyProperty CornerRadiusProperty =
          DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(MaskControl), 
              new PropertyMetadata(new CornerRadius(0)));
        public MaskControl(Visual _visual)
        {
            visual = _visual;
        }
        public CornerRadius CornerRadius
        {
            get => (CornerRadius)GetValue(CornerRadiusProperty);
            set => SetValue(CornerRadiusProperty, value);
        }
    }
}

3)創建 Loading 繼承 BaseControl 增加附加屬性 IsShow 代碼如下:

  • True 則動態添加裝飾器 AdornerContainer 并將 MaskControl 添加到 AdornerContainer.Child 中。

  • False 則移除裝飾器。

using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
using WPFDevelopers.Helpers;
using WPFDevelopers.Utilities;

namespace WPFDevelopers.Controls
{
    public class Loading : BaseControl
    {
        public static readonly DependencyProperty IsShowProperty =
           DependencyProperty.RegisterAttached("IsShow", typeof(bool), typeof(Loading),
               new PropertyMetadata(false, OnIsLoadingChanged));
        private const short SIZE = 25;
        private const double MINSIZE = 40;
        private static FrameworkElement oldFrameworkElement;
        private static void OnIsLoadingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue is bool isMask && d is FrameworkElement parent)
            {
                if (isMask)
                {
                    if (!parent.IsLoaded)
                        parent.Loaded += Parent_Loaded;
                    else
                        CreateMask(parent);
                }
                else
                {
                    parent.Loaded -= Parent_Loaded;
                    CreateMask(parent, true);
                }
            }
        }
        private static void Parent_Loaded(object sender, RoutedEventArgs e)
        {
            if (sender is UIElement element)
                CreateMask(element);
        }
        static void CreateMask(UIElement uIElement, bool isRemove = false)
        {
            var layer = AdornerLayer.GetAdornerLayer(uIElement);
            if (layer == null) return;
            if (isRemove && uIElement != null)
            {
                var adorners = layer.GetAdorners(uIElement);
                if (adorners != null)
                {
                    foreach (var item in adorners)
                    {
                        if (item is AdornerContainer container)
                        {
                            var isAddChild = (bool)Loading.GetIsAddChild(uIElement);
                            if (!isAddChild)
                                Loading.SetChild(uIElement, null);
                            container.Child = null;
                            layer.Remove(container);
                        }
                    }
                }
                return;
            }
            var adornerContainer = new AdornerContainer(uIElement);
            var value = Loading.GetChild(uIElement);
            if (value == null)
            {
                var isLoading = GetIsShow(uIElement);
                if (isLoading)
                {
                    var w = (double)uIElement.GetValue(ActualWidthProperty);
                    var h = (double)uIElement.GetValue(ActualHeightProperty);
                    var defaultLoading = new DefaultLoading();
                    if (w < MINSIZE || h < MINSIZE)
                    {
                        defaultLoading.Width = SIZE;
                        defaultLoading.Height = SIZE;
                        defaultLoading.StrokeArray = new DoubleCollection { 10, 100 };
                    }
                    SetChild(uIElement, defaultLoading);
                    value = Loading.GetChild(uIElement);
                }
                if (value != null)
                    adornerContainer.Child = new MaskControl(uIElement) { Content = value, Background = ControlsHelper.Brush };
            }
            else
            {
                var normalLoading = (FrameworkElement)value;
                var frameworkElement = (FrameworkElement)uIElement;
                Loading.SetIsAddChild(uIElement, true);

                if (oldFrameworkElement != null)
                    value = oldFrameworkElement;
                else
                {
                    string xaml = XamlWriter.Save(normalLoading);
                    oldFrameworkElement = (FrameworkElement) XamlReader.Parse(xaml);
                }

                var _size = frameworkElement.ActualHeight < frameworkElement.ActualWidth ? frameworkElement.ActualHeight : frameworkElement.ActualWidth;
                if(_size < MINSIZE)
                {
                    normalLoading.Width = SIZE;
                    normalLoading.Height = SIZE;
                    value = normalLoading;
                }
                
                adornerContainer.Child = new MaskControl(uIElement) { Content = value, Background = ControlsHelper.Brush };

            }
            layer.Add(adornerContainer);

        }
        public static bool GetIsShow(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsShowProperty);
        }

        public static void SetIsShow(DependencyObject obj, bool value)
        {
            obj.SetValue(IsShowProperty, value);
        }
    }
}

4)創建 DefaultLoading.xaml 代碼如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:controls="clr-namespace:WPFDevelopers.Controls">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Basic/ControlBasic.xaml"/>
    </ResourceDictionary.MergedDictionaries>

    <Style TargetType="{x:Type controls:DefaultLoading}">
        <Setter Property="Width" Value="40" />
        <Setter Property="Height" Value="40" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type controls:DefaultLoading}">
                    <Viewbox Width="{TemplateBinding Width}" 
                             Height="{TemplateBinding Height}">
                        <controls:SmallPanel>
                            <controls:SmallPanel.Resources>
                                <Storyboard x:Key="StarStoryboard" RepeatBehavior="Forever">
                                    <DoubleAnimation
                                                Storyboard.TargetName="PART_Ellipse"
                                                Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)"
                                                To="360"
                                                Duration="0:0:1.0" />
                                </Storyboard>
                            </controls:SmallPanel.Resources>
                            <Ellipse
                                        Width="{TemplateBinding Width}"
                                        Height="{TemplateBinding Height}"
                                        Stroke="{DynamicResource BaseSolidColorBrush}"
                                        StrokeDashArray="100,100"
                                        StrokeThickness="2" />
                            <Ellipse
                                        x:Name="PART_Ellipse"
                                        Width="{TemplateBinding Width}"
                                        Height="{TemplateBinding Height}"
                                        Stretch="Uniform"
                                        RenderTransformOrigin=".5,.5"
                                        Stroke="{DynamicResource PrimaryPressedSolidColorBrush}"
                                        StrokeDashArray="{TemplateBinding StrokeArray}"
                                        StrokeThickness="2">
                                <Ellipse.RenderTransform>
                                    <RotateTransform Angle="0" />
                                </Ellipse.RenderTransform>
                                <Ellipse.Triggers>
                                    <EventTrigger RoutedEvent="Loaded">
                                        <BeginStoryboard Storyboard="{StaticResource StarStoryboard}" />
                                    </EventTrigger>
                                </Ellipse.Triggers>
                            </Ellipse>
                        </controls:SmallPanel>
                    </Viewbox>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

5)創建 LoadingExample.xaml 實例代碼如下:

<UserControl x:Class="WPFDevelopers.Samples.ExampleViews.LoadingExample"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:wd="https://github.com/WPFDevelopersOrg/WPFDevelopers"

             xmlns:local="clr-namespace:WPFDevelopers.Samples.ExampleViews"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
        <Grid Margin="10">
            <StackPanel Grid.Column="1">
                <CheckBox Name="MyCheckBox" Content="啟動 Loading 動畫"
                          VerticalAlignment="Center"
                          HorizontalAlignment="Center"/>
                <UniformGrid Margin="10" Rows="2" Columns="3">
                    <Border Background="Red" 
                wd:Loading.IsShow="{Binding ElementName=MyCheckBox,Path=IsChecked}">
                        <TextBlock Text="Mask 0"
                       VerticalAlignment="Center" 
                       HorizontalAlignment="Center"/>
                    </Border>
                    <Image Source="pack://application:,,,/WPFDevelopers.Samples;component/Images/Breathe/0.jpg"
                   wd:Loading.IsShow="{Binding ElementName=MyCheckBox,Path=IsChecked}"
                           wd:Loading.Child="{x:Static wd:NormalLoading.Default}"/>
                    <Button Content="Mask 1" wd:Loading.IsShow="{Binding ElementName=MyCheckBox,Path=IsChecked}" Height="28"
                    VerticalAlignment="Top" HorizontalAlignment="Center"/>
                    <Button Content="Mask 2" wd:Loading.IsShow="{Binding ElementName=MyCheckBox,Path=IsChecked}"
                    VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0,10"/>
                    <Button Content="提交" wd:Loading.IsShow="{Binding ElementName=MyCheckBox,Path=IsChecked}" 
                    VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0,10"
                    Style="{StaticResource PrimaryButton}"/>
                </UniformGrid>
            </StackPanel>
        </Grid>
</UserControl>

效果圖

WPF如何實現在控件上顯示Loading等待動畫

關于“WPF如何實現在控件上顯示Loading等待動畫”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“WPF如何實現在控件上顯示Loading等待動畫”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

wpf
AI

罗源县| 西盟| 龙门县| 莆田市| 惠安县| 屯门区| 那坡县| 增城市| 济源市| 油尖旺区| 义乌市| 获嘉县| 万安县| 广昌县| 方城县| 龙里县| 凤翔县| 都匀市| 新龙县| 加查县| 紫金县| 陆良县| 盖州市| 阳信县| 阿城市| 新晃| 连江县| 张北县| 石渠县| 壶关县| 秭归县| 密云县| 嘉鱼县| 鸡东县| 定结县| 沛县| 山东省| 大英县| 吉木乃县| 郓城县| 浠水县|