无法使用foreach(C#)正确填充ObseservableCollection

我使用数组和foreach来填充列表。但是WPF GUI只向我显示数组中的最后一项,而不是全部。绑定是正确的,我的代码中必须存在逻辑错误:

public ObservableCollection<Client> Clients { get; set; }

string[] clients = { 
            "XYZ.company.server","ABC.company.server"
}

foreach (string item in clients)
{
    Client client = new Client(item);
    Clients = new ObservableCollection<Client>();
    Clients.Add(client);
}

this.DataContext = this;

Gui仅在ListView上显示“ ABC.company.server”。

quhongliang 回答:无法使用foreach(C#)正确填充ObseservableCollection

您需要在循环之前声明collection。因此,在循环时,您的集合将从foreach循环中添加项目。

Clients = new ObservableCollection<Client>();
foreach (string item in clients)
{
    Client client = new Client(item);

    Clients.Add(client);

}

否则,您的集合将在每次循环中重新创建,并且之前所有迭代的项目都不会添加到新创建的集合中。

本文链接:https://www.f2er.com/2766103.html

大家都在问