WPF中ListBox控件刷新问题

2025-05-18 18:05:52
推荐回答(1个)
回答(1):

WPF采用了与原来WinForm完全不同的刷新机制。在WPF中,只能通过Dispatcher.BeginInvoke方法来刷新UI元素

实现你要求的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfUIAsyncUpdate
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            box.Items.Add("String A");
            
            //启动一个线程
            Thread t = new Thread(LongWork);
            t.IsBackground = true;
            t.Start();
        }

        private void LongWork()
        {
            Thread.Sleep(8000); //模拟一个耗时的操作
            
            //向ListBox添加一个项 "String B"
            //由于LongWork运行在后台线程上
            //所以必须通过box.Dispatcher.BeginInvoke来刷新界面
            //这与WinForm中跨线程刷新控件有些类似
            box.Dispatcher.BeginInvoke(
                new Action(() => { box.Items.Add("String B"); }), 
                null);
        }
    }
}