通过调度程序/数据绑定在此更新 UI 中缺少什么

我有一个简单的 WPF 窗口:Loaded="StartTest" 和


<Grid>

        <ListBox ItemsSource="{Binding Logging, IsAsync=True}"></ListBox>

</Grid>

在后面的代码中,我有方法StartTest:


LogModel LogModel = new LogModel();


void StartTest(object sender, RoutedEventArgs e)

{

    DataContext = LogModel;


    for (int i = 1; i<= 10; i++)

    {

       LogModel.Add("Test");

       Thread.Sleep(100);

    }

}

类LogModel是:


public class LogModel : INotifyPropertyChanged

{

    public LogModel()

    {

        Dispatcher = Dispatcher.CurrentDispatcher;

        Logging = new ObservableCollection<string>();

    }

    Dispatcher Dispatcher;


    public ObservableCollection<string> Logging { get; set; }


    public event PropertyChangedEventHandler PropertyChanged;


    public void Add(string text)

    {

        Dispatcher.BeginInvoke((Action)delegate ()

        {

            Logging.Add(text);

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Logging"));

        });

    }

}

当然,问题是 UI 不会在循环中更新。我错过了什么?

如何实现UI更新?


弑天下
浏览 187回答 3
3回答

慕哥6287543

UI 未在循环中更新的原因是对Dispatcher.BeginInvoke.&nbsp;这会DispatcherOperation在调度程序队列中放置一个新的。但是你的循环已经是一个调度器操作,它继续在Dispatcher的线程上。因此,您排队的所有操作都将在循环操作完成后执行。也许你想StartTest在后台线程上运行?然后,UI 将更新。顺便说一句,不要用 阻塞Dispatcher的线程Thread.Sleep。它阻止Dispatcher尽可能顺利地做它的事情。

慕婉清6462132

它是DoEvents一回事,overhere:public static void DoEvents(){&nbsp; &nbsp; Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Action(delegate { }));}当然,应该以不需要它的方式编写不同的测试。
打开App,查看更多内容
随时随地看视频慕课网APP