3

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.

screenshot

       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.

1
  • 2
    +1 for a good screenshot and a code sample that contains exactly the relevant parts. Commented Oct 5, 2011 at 17:19

2 Answers 2

5

You should use an ObservableCollection<T> instead of List<T>.

ObservableCollection<T> implements INotifyCollectionChanged, which will tell WPF when you add or remove items.

Sign up to request clarification or add additional context in comments.

2 Comments

I was going to type a very similar response.
In addition : The ObservableCollection<T> notify for list change (Add, Remove, Move) but not for T change. You need T to implement INotifyPropertyChanged for that.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.