2017-04-05 191 views
0

我的中有一個,它與ObservableCollection綁定。這是一個搜索結果DataGrid。問題是,我更新搜索結果ObservableCollection後,實際DataGrid未更新。WPF ObservableCollection在創建新的ObservableCollection時未更新DataGrid

之前,我得到了投什麼,請注意這不是關於在列中的數據(即綁定完美的作品)有關清除,然後把完全新的數據到ObservableCollection未更新DataGridSo linking to something like this will not help as my properties are working correctly

背景:

ObservableCollectionViewModel這樣被聲明;

public ObservableCollection<MyData> SearchCollection { get; set; } 

綁定到我的搜索ObservableCollection這樣的搜索DataGrid;

<DataGrid ItemsSource="{Binding SearchCollection}" /> 

ViewModel我有一個像這樣的搜索方法;

var results = 
     from x in MainCollection 
     where x.ID.Contains(SearchValue) 
     select x; 
SearchCollection = new ObservableCollection<MyData>(results); 

該方法正確激發併產生所需結果。然而DataGrid沒有更新新的結果。我知道ViewModel具有正確的數據,因爲如果我在頁面上放置按鈕並在click事件中放置此代碼;

private void selectPromoButton_Click(object sender, System.Windows.RoutedEventArgs e) 
{ 
    var vm = (MyViewModel)DataContext; 
    MyDataGrid.ItemsSource = vm.SearchCollection; 
} 

DataGrid現在可以正確顯示結果。

我知道我可以把一些事件放在頁面後面的代碼中,但是不會打敗MVVM嗎?什麼是正確的MVVM方式來處理這個問題?

回答

3

嘗試實施INotifyPropertyChanged在模型視圖

例如:

public abstract class ViewModelBase : INotifyPropertyChanged { 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); 
    } 

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) 
    { 
     var handler = PropertyChanged; 
     handler?.Invoke(this, args); 
    } 
} 

public class YourViewModel : ViewModelBase { 

    private ObservableCollection<MyData> _searchCollection ; 

    public ObservableCollection<MyData> SearchCollection 
    { 
     get { return _searchCollection; } 
     set { _searchCollection = value; OnPropertyChanged("SearchCollection"); } 
    } 

} 
2

問題是您正在重置您的SearchCollection屬性而不是更新集合。當列表中的項目被添加,刪除或更新時,Observable集合會引發正確的更改事件。但是,收集屬性本身沒有改變。

在您的SearchCollection設置器中,您可以觸發PropertyChanged事件。就像任何其他財產一樣。還要確保你的DataGrid ItemsSource綁定是單向的而不是一次性的。

<DataGrid ItemsSource="{Binding SearchCollection, Mode=OneWay}" /> 

或者您可以更改集合的成員(清除舊結果並添加新結果)。這也應該如您所期望的那樣更新DataGrid。

從您的代碼示例中,我會選擇第一個選項。

相關問題