开发者

Update a single item in a DataGrid's ItemsSource

开发者 https://www.devze.com 2023-02-15 23:51 出处:网络
I have a simple problem that probably has a simple answer.I have a DataGrid displaying some items.I wish to update one of the items like so:

I have a simple problem that probably has a simple answer. I have a DataGrid displaying some items. I wish to update one of the items like so:

var old = (SomeClass)grid.SelectedItem;
var newItem = new SomeClass(...);
old = newItem;
//grid.Items.Refresh();

First, the code is trivialized in the example, but this is the important bit (the real issue is updating an object via Linq2Sql and then setting the old object to the updated one).

Anyway, I was hoping that a call to Items.Refresh would update the grid's UI, but it doesn't. I am certainly missing something in regards to how DataGrid's cache their ItemsSource elements, but I w开发者_开发百科ould imagine this is a pretty common scenario. Any idea?


You would need to get your Grid's ItemSource and update the correct item inside the ItemsSource. Right now you are making a copy of the selected item and updating that, so it does nothing.

I'm not sure the exact syntax but you'll want something like

((IEnumerable)grid.ItemsSource)[grid.SelectedIndex] = newItem;  


You will need to modify the item in the ItemsSource. And even that will only work if the item is either a DependecyObject or implements INotifyPropertyChanged

0

精彩评论

暂无评论...
验证码 换一张
取 消