【问题标题】:Refresh the DataGrid row by row when observablecollection is added during the loop?在循环期间添加observablecollection时逐行刷新DataGrid?
【发布时间】:2013-12-02 09:22:10
【问题描述】:

窗口中有一个 DataGrid,它绑定到一个 ObservableCollection,还有一个命令可以将项目列表添加到集合中。
我希望 DataGrid 可以在循环过程中逐行添加,但是现在它会在命令完成后向 DataGrid 添加一批项目。

<DataGrid ItemsSource="{Binding Path=InfoList}" AutoGenerateColumns="False">
<DataGrid.Columns>
    <DataGridTextColumn Header="Column1" Binding="{Binding Path=Field1}" />
    <DataGridTextColumn Header="Column2" Binding="{Binding Path=Field2}" />
    </DataGrid.Columns>
</DataGrid>

public class XXViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Info> infoList = new ObservableCollection<Info>();
    public ObservableCollection<Info> InfoList
    {
        get{return infoList;}           
    }

    private void XXCommand()
    {    
        List<Info> list = this.GetList();
        foreach(var item in list)
        {
            // the datagrid won't update or show this item immediately          
            this.InfoList.Add(item);
            Thread.Sleep(1000);             
        }
    }
}

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    尝试将您的添加代码添加到Dispatcher 的队列中:

    Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
    {
        InfoList.Add(item);
        Thread.Sleep(1000); 
    });
    

    【讨论】:

    • 嗨,Sheridan,感谢您的回答。 Dispatcher.CurrentDispatcher 不起作用,但它通过 currentWindow.Dispatcher.Invoke 函数起作用。
    • @Carlos 你能解释清楚吗?
    【解决方案2】:

    我们可能无法从您的代码中识别出几个问题:

    1. 您是否设置了视图的 DataContext 以便您的集合可以 在运行时找到?
    2. 您的集合类型是否包含表的给定字段 列?
    3. 您是否在 ui 线程或其他线程中初始化了视图模型?

    我倾向于认为第 1 点是一个受欢迎的问题。

    【讨论】:

    • 嗨,Jan 谢谢你的回答。我已在 xaml 代码中将 viewmodel 实例绑定为窗口 DataContext,并且列绑定字段/proerty 在 Info 类中退出。主要问题是向 ObservableCollection 添加行时如何刷新数据网格。
    猜你喜欢
    • 2012-02-24
    • 2016-05-19
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2021-10-20
    • 2014-02-01
    • 1970-01-01
    • 2017-02-22
    相关资源
    最近更新 更多