Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

c# - Why does the DataGrid not update when the ItemsSource is changed?

I have a datagrid in my wpf application and I have a simple problem. I have a generic list and I want to bind this collection to my datagrid data source every time an object is being added to the collection. and I'm not interested to use observable collection.

the point is I'm using the same method somewhere else and that works fine. but this time when i press Add button an object is added and datagrid updates correctly but from the second item added to collection datagrid does not update anymore.

Here is the Code :

 private void btnAddItem_Click(object sender, RoutedEventArgs e)
    {
        OrderDetailObjects.Add(new OrderDetailObject
        {
            Price = currentitem.Price.Value,
            Quantity = int.Parse(txtQuantity.Text),
            Title = currentitem.DisplayName,
            TotalPrice = currentitem.Price.Value * int.Parse(txtQuantity.Text)
        });

        dgOrderDetail.ItemsSource = OrderDetailObjects;
        dgOrderDetail.UpdateLayout();
    }

any idea ?

question from:https://stackoverflow.com/questions/7059070/why-does-the-datagrid-not-update-when-the-itemssource-is-changed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The ItemsSource is always the same, a reference to your collection, no change, no update. You could null it out before:

dgOrderDetail.ItemsSource = null;
dgOrderDetail.ItemsSource = OrderDetailObjects;

Alternatively you could also just refresh the Items:

dgOrderDetail.ItemsSource = OrderDetailObjects; //Preferably do this somewhere else, not in the add method.
dgOrderDetail.Items.Refresh();

I do not think you actually want to call UpdateLayout there...

(Refusing to use an ObservableCollection is not quite a good idea)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...