WPF窗口更新 [英] WPF window update

查看:87
本文介绍了WPF窗口更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为应该是一个简单的任务而苦苦挣扎;在WPF程序中更新用户界面以反映进度.我知道有不同的方法可以执行此操作,但是请有人指出这种简单方法的错误之处吗?

谢谢,stegzzz

Hi, I''m struggling with what should be a simple task; update the user interface in a WPF program to reflect progress. I know there are different ways to do this but please can someone point out where I''m going wrong with this simple approach?

Thanks, stegzzz

/// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        delegate void MDFunc(int i);

        //after clicking the Go button a set of calls to Func are queued
        private void Go(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 10; i++)
                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new MDFunc(Func), i);

        }

        //each time Func is called (from the dispatcher queue) it should update the button content so the user sees
        //the task progress
        void Func(int i)
        {
            Stopwatch S = new Stopwatch();
            S.Start();
            while (S.ElapsedMilliseconds < 500)
            { }

            button1.Content = i.ToString();
            button1.InvalidateVisual();
        }
    }

推荐答案

计时器线程应执行while循环,并以所需的时间间隔将消息发送回表单,然后可以使用Dispatcher.Invoke更新按钮.


至少,这就是我要做的方式.
The timer thread should perform the while loop and at the desired interval, send a message back to the form which can then use Dispatcher.Invoke to update the button.


At least, that''s the way I''d do it.


事实证明,上面概述的方法实际上是可以的,但由于以下原因似乎不起作用DispatcherPriority.Normal

将DispatcherPriority设置为低于渲染的级别具有所需的效果,因为屏幕更新以反映通过Go循环中设置的Func的i调用的进度.大概,当优先级正常时,所有对Func的调用都在下一次渲染操作之前完成,这就是为什么我没有看到屏幕更新的原因.
John的另一个建议对于表单应用程序可能还可以吗?

Chrs,stegzzz
It turns out that the approach sketched above, in the question, is actually OK but appears not to work because of DispatcherPriority.Normal

Setting DispatcherPriority to a lower level than render has the desired effect, in that the screen updates to reflect progress through the i calls of Func which are setup in the Go loop. Presumeably, when priority is normal, all of the calls to Func get completed before the next render operation and that''s why I wasn''t seeing the screen update.

The other suggestion from John maybe is OK for a forms application?

Chrs, stegzzz


这篇关于WPF窗口更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆