c# - 刷新 UI 以反射(reflect)添加到列表中的项目

标签 c# winforms background

在显示我的 UI 时,数据正在后端传递并添加到 List<string>我又想在我的用户界面上显示。

我见过几个使用后台工作程序的示例,但是由于我如何布局我的用户控件并以编程方式构建它们,我无法访问实际组件。

问题:如何在我的 UI 后面重复运行此方法,而不会在循环中锁定我的 UI?

public void UpdatePanel()
{
    foreach (var item in list)
    {
        AddMethod(item);
    }
}

最佳答案

如果可能,您可以使用 BindingList<T> 作为一种选择,而不是使用循环或时间间隔来监视列表。或 ObservableCollection<T> 并在列表更改时收到通知。

然后您可以在您访问的事件处理程序中更新用户界面 ListChanged BindingList<T>的事件或 CollectionChanged ObservableCOllection<T>的事件.

示例

这是一个基于 ObservableCollection<string> 的例子.

ObservableCollection<string> list;
private void Form1_Load(object sender, EventArgs e)
{
    list = new ObservableCollection<string>();
    list.CollectionChanged += list_CollectionChanged;
    list.Add("Item 1");
    list.Add("Item 2");
    list.RemoveAt(0);
    list[0] = "New Item";
}
void list_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.Action == NotifyCollectionChangedAction.Add)
    {
        var items = string.Join(",", e.NewItems.Cast<String>());
        MessageBox.Show(string.Format("'{0}' Added", items));
    }
    else if (e.Action == NotifyCollectionChangedAction.Remove)
    {
        var items = string.Join(",", e.OldItems.Cast<String>());
        MessageBox.Show(string.Format("'{0}' Removed", items));
    }
    else if (e.Action == NotifyCollectionChangedAction.Replace)
    {
        var oldItems = string.Join(",", e.OldItems.Cast<String>());
        var newItems = string.Join(",", e.NewItems.Cast<String>());
        MessageBox.Show(string.Format("'{0}' replaced by '{1}'", oldItems, newItems));
    }
    else
    {
        MessageBox.Show("Reset or Move");
    }
}

关于c# - 刷新 UI 以反射(reflect)添加到列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39131962/

相关文章:

background - 从多任务处理回来后如何恢复 CAAnimation

windows - 使 Powershell 函数/任务在后台运行

c# - FrameworkElementFactory 信息

c# - 在 VS 调试器中运行时出现带有 ChromiumFX "failed to establish GPU channel"错误的 CEF

c# - 将时间跨度转换为日期时间添加到 C# 中的日期时间选择器

c# - 以安全的方式发送电子邮件

Android背景图片内存使用情况

c# - 断路器模式中异常过滤的一些实现是什么?

c# - Selenium 测试项目 C# 未运行 Chrome

c# - 在等待时,当控制权转到调用者时,它是否处理 for 循环的下一次迭代(等待返回任务吗?)?