WPF DataGrid is not rendered properly after Changing underlying collection
Here's my code:
<Grid>
<Button Content="Button" Click="button1_Click" />
<DataGrid ItemsSource ="{Binding Lst}" />
</Grid>
Code-Behind:
private void button1_Click(object sender, RoutedEventArgs e)
{
(this.DataContext as Some).remove();
}
DataSource is:
public class Some : INotifyPropertyChanged
{
private List<Point> lst = new List<Point>();
public List<Point> Lst
{
get
{
return lst;
}
}
publi开发者_如何学编程c Some()
{
lst.Add(new Point(2.3, 5));
lst.Add(new Point(267.3, 5));
lst.Add(new Point(2.3, 65));
lst.Add(new Point(2.63, 885));
lst.Add(new Point(27.3, 65));
}
public void remove()
{
lst.Remove(lst.Last());
if (PropertyChanged != null)
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Lst"));
}
public event PropertyChangedEventHandler PropertyChanged;
}
When i call remove()
method, i delete item from the collection and invoke propertychanged. UI reaction is: i cannot properly select cells in datagrid which correspond to deleted Point
. They are not removed. This looks like UI bug, is there any workaround?
Sorry for it's so dirty - just a quick sample.
Thanks, Ilya
Use ObservableCollection<>
instead of List<>
for Lst - the ObservableCollection automatically notifies when the collection changes through adds, removes or clears. You will also need a DependencyProperty: http://forums.silverlight.net/forums/t/12664.aspx
I case of binding ItemSource
to a view model, your collection should implement INotifyCollectionChanged
. The ObsevableCollection
in fact is the collection that implements INotifyCollectionChanged
, thus notifying WPF controls of the added and removed elements.
精彩评论