如何在不覆盖旧项目的情况下向DataGrid添加新项目?

时间:2014-04-19 13:30:21

标签: c# wpf datagrid

我知道没有Append,但我相信这是调用它的正确方法(对吧?)。

现在我有一个ObservableCollection我用来向我的DataGrid添加新项目。它工作正常,但如果我一次添加10个项目,第二次添加15个项目,我最终会有15个项目,而不是25个。基本上,该集合会覆盖旧项目上的每个集合。

可以遍历旧集合并在我添加新集合后再次添加它,但这似乎是非常愚蠢的事情。我确信必须有另一种方法来做到这一点。

以下是我的内部集合类(I have used code from here)

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

    }

}

2 个答案:

答案 0 :(得分:2)

ObservableCollection在添加,删除项目或刷新整个列表时提供通知。 因此,您只需项添加到您的数据网格所绑定的ObservableCollection<ProxiesList>的同一个实例中。

基本上,您可以将mw.dataGrid1.ItemsSource设置为ObservableCollection<ProxiesList>或使用Xaml中的Binding

每次添加项目时都不需要设置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设置为_GridItems,则可以将Xaml中的ProxiesList绑定到DataContext媒体资源。

除了您的属性命名之外,最好遵循C#命名约定。

答案 1 :(得分:1)

ObservableCollection内置了一种机制,可以在项目添加到集合或从集合中删除时通知UI(在这种情况下为DataGrid)。

因此,实例化ObservableCollection并设置DataGrid&#39; s ItemsSource一次就足够了。例如,您可以在构造函数中执行此操作。其余的只是向现有集合添加新项目:

public ProxiesList()
{
    GridItems = new ObservableCollection<ProxiesList>();
    mw.dataGrid1.ItemsSource = 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"
        });
    }
}

...而且我没有看到将_GridItems保留在此处的好处,因此您可以将其删除。