简体   繁体   English

如何将List <object>动态绑定到WPF中的DataGrid?

[英]How to bind List<object> dynamically to a DataGrid in WPF?

i want to bind list to a datagrid dynamically, following code works for first time, if click add again it is not getting populated in the data grid. 我希望动态地将列表绑定到数据网格,以下代码首次运行,如果再次单击添加,则不会在数据网格中填充。

截图

       private List<Item> PopulateItemList()
    {
        return itemLst;
    }
    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        Item item = new Item();
        item.Item1 = txtItem.Text;
        itemLst.Add(item);
        grdItem.ItemsSource = PopulateItemList();

    }
    private List<Item> itemLst = new List<Item>();

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        itemLst.Clear(); 

    }

Thanks. 谢谢。

You should use an ObservableCollection<T> instead of List<T> . 您应该使用ObservableCollection<T>而不是List<T>

ObservableCollection<T> implements INotifyCollectionChanged , which will tell WPF when you add or remove items. ObservableCollection<T>实现了INotifyCollectionChanged ,它将告诉WPF何时添加或删除项目。

Either you should use ObservableCollection as suggested by Slaks. 您应该使用Slaks建议的ObservableCollection。 Otherwise you have to set the datatgrid itemSource null first before populating it again to some other value. 否则,您必须先将datatgrid itemSource设置为null,然后再将其再次填充到其他值。 But i would strongly suggest you to use ObservableCollection and you can set it to datagrid's ItemSource in the UserControl's constructor instead of setting it again. 但我强烈建议你使用ObservableCollection,你可以在UserControl的构造函数中将它设置为datagrid的ItemSource,而不是再次设置它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM