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

使用foreach(C#)无法正确填充ObservableCollection,c#,arrays,list,foreach,observablecollection,C#,Arrays,List,Foreach,Observablecollection,我使用数组和foreach来填充列表。但是WPF GUI只显示数组中的最后一项,而不是全部。绑定正确,我的代码中一定有逻辑错误: public ObservableCollection<Client> Clients { get; set; } string[] clients = { "XYZ.company.server", "ABC.company.server" } foreach (string item in clie

我使用数组和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;
publicobservableCollection客户端{get;set;}
字符串[]客户端={
“XYZ.company.server”,
“ABC.company.server”
}
foreach(客户端中的字符串项)
{
客户=新客户(项目);
Clients=新的observeCollection();
客户。添加(客户);
}
this.DataContext=this;

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

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

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

    Clients.Add(client);

}
Clients=newobserveCollection();
foreach(客户端中的字符串项)
{
客户=新客户(项目);
客户。添加(客户);
}

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

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

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

    Clients.Add(client);

}
Clients=newobserveCollection();
foreach(客户端中的字符串项)
{
客户=新客户(项目);
客户。添加(客户);
}

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

您正在每个循环迭代中创建
客户端。将
Clients=newobservedcollection()
放在每个循环迭代中要创建的
Clients
循环之前。将
Clients=newobservedcollection()
放在循环之前