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

如何解决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(); 
        }));
    }

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-