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
290 views
in Technique[技术] by (71.8m points)

c# - Re-sort WPF DataGrid after bounded Data has changed

I am looking for a way to re-sort my DataGrid when the underlying data has changed.

(The setting is quite standard: The DataGrid's ItemSource property is bound to an ObservableCollection; The columns are DataGridTextColumns; The data inside the DataGrid reacts correctly on changes inside the ObservableCollection; Sorting works fine when clicked with the mouse)

Any ideas ?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It took me the whole afternoon but I finally found a solution that is surprisingly simple, short and efficient:

To control the behaviors of the UI control in question (here a DataGrid) one might simply use a CollectionViewSource. It acts as a kind of representative for the UI control inside your ViewModel without completely breaking the MVMM pattern.

In the ViewModel declare both a CollectionViewSource and an ordinary ObservableCollection<T> and wrap the CollectionViewSource around the ObservableCollection:

// Gets or sets the CollectionViewSource
public CollectionViewSource ViewSource { get; set; }

// Gets or sets the ObservableCollection
public ObservableCollection<T> Collection { get; set; }

// Instantiates the objets.
public ViewModel () {

    this.Collection = new ObservableCollection<T>();
    this.ViewSource = new CollectionViewSource();
    ViewSource.Source = this.Collection;
}

Then in the View part of the application you have nothing else to do as to bind the ItemsSource of the CollectionControl to the View property of the CollectionViewSource instead of directly to the ObservableCollection:

<DataGrid ItemsSource="{Binding ViewSource.View}" />

From this point on you can use the CollectionViewSource object in your ViewModel to directly manipulate the UI control in the View.

Sorting for example - as has been my primary problem - would look like this:

// Specify a sorting criteria for a particular column
ViewSource.SortDescriptions.Add(new SortDescription ("columnName", ListSortDirection.Ascending));

// Let the UI control refresh in order for changes to take place.
ViewSource.View.Refresh();

You see, very very simple and intuitive. Hope that this helps other people like it helped me.


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

...