我知道没有Append
,但是我相信这是调用它的正确方法(对吗?)。
现在我有一个ObservableCollection
,可以用来向其中添加新项目DataGrid
。效果很好,但是如果我一次添加10个项目,第二次添加15个项目,则最终得到15个项目,而不是25个。基本上,该集合会覆盖旧集合中的每个集合。
我可以遍历旧集合并在包含新集合后再次添加它,但这似乎很愚蠢。我确信必须有另一种方法来做到这一点。
这是我的内部集合里面的类的样子(我从这里使用了代码):
public class ProxiesList
{
public string proxy { get; set; }
public string proxySource { get; set; }
public bool proxyUsed { get; set; }
public bool toUse { get; set; }
public string working { get; set; }
ObservableCollection<ProxiesList> GridItems = new ObservableCollection<ProxiesList>();
public ObservableCollection<ProxiesList> _GridItems
{
get
{
return GridItems;
}
}
public void addTheData(MainWindow mw, List<string> proxyList)
{
foreach (string line in proxyList)
{
_GridItems.Add(new ProxiesList //add items to the collection
{
proxy = line.Split(';')[0],
proxySource = line.Split(';')[1],
proxyUsed = false,
toUse = true,
working = "n/a"
});
}
mw.dataGrid1.ItemsSource = GridItems; //bind the collection to the dataGrid1
GridItems = new ObservableCollection<ProxiesList>(); //create new instance of the observable collection
}
}
ObservableCollection在添加,删除项或刷新整个列表时提供通知。因此,您只需要将您的项目附加到ObservableCollection<ProxiesList>
您的数据网格所绑定到的同一实例。
因此,基本上,您可以将其设置mw.dataGrid1.ItemsSource
为ObservableCollection<ProxiesList>
或Binding
在Xaml中使用。
您无需在mw.dataGrid1.ItemsSource
每次添加项目时进行设置。
GridItems = new ObservableCollection<ProxiesList>(); //create new instance of the observable collection
此行导致了您的问题,因为它创建了该集合的新实例,因此每次将项目添加到的新实例时ObservableCollection<ProxiesList>
,这意味着它仅包含您刚刚添加的项目。
因此,只需从您的行中删除以下几行 public void addTheData(MainWindow mw, List<string> proxyList)
mw.dataGrid1.ItemsSource = GridItems; //bind the collection to the dataGrid1
GridItems = new ObservableCollection<ProxiesList>(); //create new instance of the observable collection
如果您将DataGrid.ItemsSource
Xaml中的设置为,_GridItems
则可以将Xaml中的绑定到您的属性。ProxiesList
DataContext
以及其他类似属性命名的事情,最好遵循C#命名约定。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句