简体   繁体   中英

Gridview doesn't change when data changes

I've added an observable data and bound it to my data grid as follows.

private ObservableCollection<Order> _allOrders;
public ObservableCollection<Order> AllOrders
{
  get { return _allOrders;}
  set { _allOrders = value; OnPropertyChanged(); }
}

public Presenter() { _allOrders = new ObservableCollection<Order>(...); }

public event PropertyChangedEventHandler PropertyChanged;

[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] String propertyName = null)
{
  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

When I set breakpoint on the event that is supposed to filter the data, I set the property AllOrder to null . I can verify using the watch that it's set to that. However, the view isn't updated, so I'm guessing that I forgot something. The view model class Presenter implements INotifyPropertyChanged interface, of course.

What's missing?

Edit

The XAML code for the grid looks as follows.

<DataGrid x:Name="dataGrid" 
          ItemsSource="{Binding AllOrders}"
          AutoGeneratingColumn="DataGrid_OnAutoGeneratingColumn" ...>

Assuming that you set DataContext accordingly and AllOrders binding works initially if you want to filter items in the UI, without change collection, it's much easier when you use ListCollectionView with a Filter . WPF does not bind directly to collection but to a view - MSDN .

private readonly ObservableCollection<Order> _allOrders;

private readonly ListCollectionView _filteredOrders;

public ICollectionView FilteredOrders 
{ 
    get { return _filteredOrders; } 
}

public Presenter() 
{ 
    _allOrders = new ObservableCollection<Order>(...);
    _filteredOrders = new ListCollectionView(_allOrders); 
    _filteredOrders.Filter = o => ((Order)o).Active;
}

and in XAML

<DataGrid ... ItemsSource="{Binding FilteredOrders}">

when you want to manually refresh UI just call Refresh

_filteredOrders.Refresh();

Apart from that nothing changes in the view model. You still add/remove items to _allItems and changes should be picked up automatically by UI

Do you set the property AllOrders only in the constructor? If so, then do not set the field _allOrders but the property AllOrders . If you set the field then notification is never raised.

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