C#WPF如何在向Stackpanel添加许多UI元素时保持应用程序响应

问题描述

我制作了一个应用程序,在其中将许多网格添加到for循环中的某些Stackpanels中。我的问题是,在for循环加载时,我的应用程序没有响应,并且我的Loadinganimation被冻结。如何在不影响UI线程的情况下将网格添加到Stackpanel,所以我的“加载动画”不会冻结。

预先感谢

编辑:

网格创建方法

        public void GridExample()
        {
            for(int i = 0; i < 120; i++)
            {
                Grid Grid1 = new Grid();
                Grid1.FlowDirection = FlowDirection.LeftToRight;
                Grid1.Width = 200;
                Grid1.Background = new SolidColorBrush(Color.FromArgb(255,(byte)33,(byte)33));
                Grid1.Margin = new Thickness(5,20,5,20);

                ColumnDeFinition Grid1_col1 = new ColumnDeFinition();
                Grid1.ColumnDeFinitions.Add(Grid1_col1);

                RowDeFinition Grid1_row1 = new RowDeFinition();
                RowDeFinition Grid1_row2 = new RowDeFinition();
                RowDeFinition Grid1_row3 = new RowDeFinition();
                RowDeFinition Grid1_row4 = new RowDeFinition();
                Grid1.RowDeFinitions.Add(Grid1_row1);
                Grid1.RowDeFinitions.Add(Grid1_row2);
                Grid1.RowDeFinitions.Add(Grid1_row3);
                Grid1.RowDeFinitions.Add(Grid1_row4);

                Grid1_row1.Height = new GridLength(255);
                Grid1_row2.Height = new GridLength(60);
                Grid1_row3.Height = new GridLength(5);
                Grid1_row4.Height = new GridLength(55);


                //Adds Grid to HomePage
                homepage1_mainstackpanel1.Children.Add(Grid1);

                Image Image1 = new Image();
                Image1.Stretch = Stretch.Fill;
                Image1.source = new BitmapImage(new Uri("Image.png"));
                Grid.SetRow(Image1,0);
                Grid1.Children.Add(Image1);


                Label Label1 = new Label();
                Label1.Content = "Example Text";
                Label1.FontSize = 15;
                Label1.Foreground = new SolidColorBrush(Colors.White);
                Label1.VerticalAlignment = VerticalAlignment.Center;
                Label1.HorizontalAlignment = HorizontalAlignment.Center;
                Grid.SetRow(Label1,1);
                Grid1.Children.Add(Label1);


                Line Line1 = new Line();
                Line1.X1 = 1;
                Line1.strokeThickness = 2;
                Line1.stroke = new SolidColorBrush(Color.FromArgb(255,(byte)51,(byte)51));
                Line1.Stretch = Stretch.Fill;
                Grid.SetRow(Line1,2);
                Grid1.Children.Add(Line1);


                Button Button1 = new Button();
                Button1.Content = "Play";
                Button1.FontSize = 15;
                Button1.Foreground = new SolidColorBrush(Colors.White);
                Button1.Background = new SolidColorBrush(Color.FromArgb(255,(byte)33));
                Button1.BorderThickness = new Thickness(0);
                Button1.VerticalAlignment = VerticalAlignment.Center;
                Button1.HorizontalAlignment = HorizontalAlignment.Center;
                Button1.Click += new RoutedEventHandler((sender,e) =>
                {
                    this.NavigationService.Navigate(new WatchPage1());
                });
                Grid1.Children.Add(Button1);

            }
        }

首页中加载动画:

public static dispatcher mainthread_dispatcher = dispatcher.Currentdispatcher;

        public HomePage1()
        {
            Loaded += Page_loaded;
            InitializeComponent();
        }

        private void Page_loaded(object sender,RoutedEventArgs e)
        {
            using (LoadingAnimation loadanimation = new LoadingAnimation(GridExample))
            {
                loadanimation.ShowDialog();
            }
        }

LoadingAnimation.xaml:

<Window x:Class="Spaceflix_Desktop.LoadingAnimation"
             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:local="clr-namespace:Spaceflix_Desktop"
             mc:Ignorable="d" 
             Height="110" Width="90" Loaded="Animation_Loaded">

    <Window.Resources>
        <Storyboard x:Key="Storyboard1" RepeatBehavior="Forever">
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse1">
                <EasingColorKeyFrame KeyTime="0" Value="#B25B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="#005B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.7" Value="sc#0,0.104616486,0.104616486"/>
                <EasingColorKeyFrame KeyTime="0:0:1" Value="sc#0,0.104616486"/>
                <EasingColorKeyFrame KeyTime="0:0:1.4" Value="#B25B5B5B"/>
            </ColorAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse2">
                <EasingColorKeyFrame KeyTime="0" Value="#FF5B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="#7F5B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.7" Value="#005B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:1" Value="sc#0,0.104616486"/>
                <EasingColorKeyFrame KeyTime="0:0:1.4" Value="#FF5B5B5B"/>
            </ColorAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse3">
                <EasingColorKeyFrame KeyTime="0" Value="#005B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="#B25B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.7" Value="#005B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:1" Value="sc#0,0.104616486"/>
                <EasingColorKeyFrame KeyTime="0:0:1.4" Value="sc#0,0.104616486"/>
            </ColorAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse4">
                <EasingColorKeyFrame KeyTime="0" Value="#005B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="#FF5B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.7" Value="#7F5B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:1" Value="#005B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:1.4" Value="sc#0,0.104616486"/>
            </ColorAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse5">
                <EasingColorKeyFrame KeyTime="0" Value="#005B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="sc#0,0.104616486"/>
                <EasingColorKeyFrame KeyTime="0:0:0.7" Value="#B25B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:1" Value="#005B5B5B"/>
            </ColorAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse6">
                <EasingColorKeyFrame KeyTime="0" Value="#005B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="sc#0,0.104616486"/>
                <EasingColorKeyFrame KeyTime="0:0:0.7" Value="#FF5B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:1" Value="#7F5B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:1.4" Value="#005B5B5B"/>
            </ColorAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse7">
                <EasingColorKeyFrame KeyTime="0" Value="#005B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="sc#0,0.104616486"/>
                <EasingColorKeyFrame KeyTime="0:0:0.7" Value="sc#0,0.104616486"/>
                <EasingColorKeyFrame KeyTime="0:0:1" Value="#B25B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:1.4" Value="#005B5B5B"/>
            </ColorAnimationUsingKeyFrames>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse8">
                <EasingColorKeyFrame KeyTime="0" Value="#7F5B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.3" Value="#005B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:0.7" Value="sc#0,0.104616486"/>
                <EasingColorKeyFrame KeyTime="0:0:1" Value="#FF5B5B5B"/>
                <EasingColorKeyFrame KeyTime="0:0:1.4" Value="#7F5B5B5B"/>
            </ColorAnimationUsingKeyFrames>
        </Storyboard>
    </Window.Resources>

   
    <Window.Triggers>
        <EventTrigger RoutedEvent="FrameworkElement.Loaded">
            <BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
        </EventTrigger>
    </Window.Triggers>


        <Border x:Name="Border" BorderBrush="#c62828" BorderThickness="2" Background="Black" Height="80" Width="80">
            <Grid x:Name="maingrid" Background="Transparent">
                <Ellipse x:Name="ellipse1" Fill="#FF5B5B5B" HorizontalAlignment="Center" Margin="0,0" Height="15" VerticalAlignment="Top" Width="15"/>
                <Ellipse x:Name="ellipse2" Fill="#FF5B5B5B" HorizontalAlignment="Right" Margin="0,15,0" Height="15" VerticalAlignment="Top" Width="15"/>
                <Ellipse x:Name="ellipse3" Fill="#FF5B5B5B" HorizontalAlignment="Right" Margin="0,0" Height="15" VerticalAlignment="Center" Width="15"/>
                <Ellipse x:Name="ellipse4" Fill="#FF5B5B5B" HorizontalAlignment="Right" Margin="0,15" Height="15" VerticalAlignment="Bottom" Width="15"/>
                <Ellipse x:Name="ellipse5" Fill="#FF5B5B5B" HorizontalAlignment="Center" Margin="0,5" Height="15" VerticalAlignment="Bottom" Width="15"/>
                <Ellipse x:Name="ellipse6" Fill="#FF5B5B5B" HorizontalAlignment="Left" Margin="15,15" Height="15" VerticalAlignment="Bottom" Width="15"/>
                <Ellipse x:Name="ellipse7" Fill="#FF5B5B5B" HorizontalAlignment="Left" Margin="5,0" Height="15" VerticalAlignment="Center" Width="15"/>
                <Ellipse x:Name="ellipse8" Fill="#FF5B5B5B" HorizontalAlignment="Left" Margin="15,0" Height="15" VerticalAlignment="Top" Width="15"/>
            </Grid>
        </Border>

</Window>

LoadingAnimation.cs:

using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Threading;
using System.Windows.Threading;
using System.Windows.Media.Animation;
using System.Windows.Controls.Primitives;
using System.ComponentModel;
using System.Runtime.Remoting.Channels;
using System.Windows.Media.Media3D;
using System.Windows.Interop;

namespace Test_Application
{
    /// <summary>
    /// Interaktionslogik für LoadingAnimation.xaml
    /// </summary>

    public partial class LoadingAnimation : Window,Idisposable
    {
        public Action Worker { get; set; }

        public LoadingAnimation (Action worker)
        {
            InitializeComponent();

            Worker = worker ?? throw new ArgumentNullException();
        }

        public void Animation_Loaded(object sender,RoutedEventArgs e)
        {
            Task.Factory.StartNew(() => { }).ContinueWith(t => HomePage1.mainthread_dispatcher.Invoke(() => Worker()),TaskScheduler.FromCurrentSynchronizationContext()).ContinueWith(t => dispatcher.Invoke(() => Close()));
        }

        public void dispose()
        {
        }
    }
}

我希望这些信息足够

解决方法

在我很长时间没有这个项目的时间之后,我现在再次处理它并找到了解决方案。我无法在新任务或线程中将网格添加到堆栈面板中,但至少可以平滑显示加载动画。由于必须将网格添加到主线程,因此我在新线程中运行了加载动画。所以我不得不将其显示为弹出窗口。这是我找到的最佳解决方案。

这是主页上的代码:

        var PositionWindow = (Window)Parent;
        int CenterX = 8;
        int CenterY = 1;
        Point CenterPoints = new Point(PositionWindow.Left + CenterX + (PositionWindow.Width / 2),PositionWindow.Top + CenterY + (PositionWindow.Height / 2));

        Thread LoadThread = new Thread(new ThreadStart(() => {
            using (PopUpLoadingAnimation loadanimation = new PopUpLoadingAnimation(GridExample,CenterPoints,PositionWindow))
            {
                loadanimation.StartTask();
                Dispatcher.Run();
            }
        }));
        LoadThread.SetApartmentState(ApartmentState.STA);
        LoadThread.Start();

我必须自己计算窗口的中间位置,以使PopUp居中。

这是PopUpLoadingAnimation.cs的代码:

public partial class PopUpLoadingAnimation : Popup
{
    public Action Worker { get; set; }
    private Point _PlacementPoints { get; set; }
    private Window MainWindow { get; set; }


    public PopUpLoadingAnimation (Action worker,Point PlacementPoints,Window mainthreadwindow)
    {
        InitializeComponent();

        Worker = worker ?? throw new ArgumentNullException();
        MainWindow = mainthreadwindow;
        _PlacementPoints = PlacementPoints;
    }

    public void StartTask()
    {
        Task.Factory.StartNew(() => Dispatcher.Invoke(() => 
        {
            Storyboard animationboard = Resources["Storyboard1"] as Storyboard;
            animationboard.Begin(maingrid);

            LoadingPopup.Placement = PlacementMode.Center;
            LoadingPopup.HorizontalOffset = _PlacementPoints.X;
            LoadingPopup.VerticalOffset = _PlacementPoints.Y;
            LoadingPopup.IsOpen = true;

            HomePage1.mainthread_dispatcher.Invoke(() => MainWindow.IsEnabled = false);

        })).ContinueWith(t => HomePage1.mainthread_dispatcher.Invoke(() => Worker()),HomePage1.mainthread_scheduler).ContinueWith(t => Dispatcher.Invoke(async () => 
        {
            LoadingPopup.IsOpen = false;
            HomePage1.mainthread_dispatcher.Invoke(() => MainWindow.IsEnabled = true);
            Dispatcher.InvokeShutdown(); 
        }));
    }

顺便感谢您的回答,不幸的是他们没有帮助