问题描述
我是 WPF 新手,所以我认为这很简单.我有一个带有列表框和按钮的表单.在按钮的单击处理程序中,我迭代地执行生成字符串的操作,我想在获取字符串时将其放入列表框中.列表框的 xaml 就像
I am new to WPF, so I thought this was simple. I have a form with a listbox and a button. In the click handler for the button I do something iteratively that generates strings, which I want to put in the listbox as I get them. The xaml for the list box is like
<ListBox Height="87" Margin="12,0,12,10" Name="lbxProgress" VerticalAlignment="Bottom">
<ListBox.BindingGroup>
<BindingGroup Name="{x:Null}" NotifyOnValidationError="False" />
</ListBox.BindingGroup>
</ListBox>
点击处理程序就像
private void btn_Click(object sender, RoutedEventArgs e)
{
List<String> lstrFiles= new List<String>(System.IO.Directory.GetFiles ("C:\temp", "*.tmp");
foreach(string strFile in lstrFiles)
lbxProgress.Items.Add(strFile);
}
非常简单.由于我的实际操作很长,我希望列表框在每次添加时都更新 - 如何让框在每次添加时动态更新?
Pretty straightforward. Since my real operation is lengthy, I want the listbox to update as I do each one - how do I get the box to dynamically update on each addition?
推荐答案
创建一个 ObservableCollection
并将您的 ListBox.ItemsSource 设置为该集合.因为集合是可观察的,所以 ListBox 将随着其内容的变化而更新.
Create an ObservableCollection<string>
and set your ListBox.ItemsSource to that collection. Because the collection is observable, the ListBox will update as its contents change.
但是,如果您的实际操作阻塞了 UI 线程,这可能会阻止 WPF 在操作完成之前更新 UI(因为 WPF 数据绑定基础结构没有机会运行).因此,您可能需要在后台线程上运行冗长的操作.在这种情况下,由于 WPF 跨线程限制,您将无法从后台线程更新 ObservableCollection(您可以更新属性,但不能更新集合).要解决此问题,请使用 Dispatcher.BeginInvoke() 在 UI 线程上更新集合,同时在后台线程上继续操作.
However, if your real operation is blocking the UI thread, this may prevent WPF from updating the UI until the operation completes (because the WPF data binding infrastructure doesn't get a chance to run). So you may need to run your lengthy operation on a background thread. In this case, you will not be able to update the ObservableCollection from the background thread due to WPF cross-threading restrictions (you can update properties, but not collections). To get around this, use Dispatcher.BeginInvoke() to update the collection on the UI thread while continuing your operation on the background thread.
这篇关于WPF 列表框动态填充 - 如何让它刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!