简体   繁体   中英

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> implements INotifyCollectionChanged , which will tell WPF when you add or remove items.

Either you should use ObservableCollection as suggested by Slaks. Otherwise you have to set the datatgrid itemSource null first before populating it again to some other value. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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