I'm trying to bind an ObservableCollection<T>
to a DataGrid
in WPF.
Below the DataGrid
, there are fields to edit the currently selected item from the DataGrid
like so:
So the generic T
of the ObservableCollection<T>
has the following properties:
- Title (Überschrift)
- Description (Beschreibung)
- Path (Pfad)
and it also has a property Reihenfolge
which means Order
.
With the yellow arrows, I want to be able to modify the order of the entries.
Unfortunately, the ObservableCollection
doesn't have an OrderBy
-method...
I've tried the following:
In XAML I have defined a CollectionViewSource
like this:
<CollectionViewSource Source="{Binding Bilder}" x:Key="Pictures">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Reihenfolge" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
And I have binded the DataGrid
to this CollectionViewSource
<DataGrid Grid.Column="0" Grid.Row="1"
Name="PictureDataGrid"
ItemsSource="{Binding Source={StaticResource Pictures}}"
AutoGenerateColumns="False"
IsReadOnly="True"
CanUserAddRows="false"
SelectedItem="{Binding SelectedBild}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
...
In the ViewModel, I have these properties:
public ObservableCollection<BildNotifiableModel> Bilder { get; set; }
public BildNotifiableModel SelectedBild { get; set; }
and two methods which are called with DelegateCommands
that update the order
private void MoveSeiteUp()
{
const int smallestReihenfolge = 1;
if (this.SelectedBild.Reihenfolge > smallestReihenfolge) {
var bildToSwapReihenfolgeWith = this.Bilder.Single(b => b.Reihenfolge == this.SelectedBild.Reihenfolge - 1);
this.SelectedBild.Reihenfolge--;
bildToSwapReihenfolgeWith.Reihenfolge++;
RaisePropertyChanged(nameof(this.Bilder));
}
}
private void MoveSeiteDown()
{
if (this.SelectedBild.Reihenfolge < MaxAllowedImages) {
var bildToSwapReihenfolgeWith = this.Bilder.Single(b => b.Reihenfolge == this.SelectedBild.Reihenfolge + 1);
this.SelectedBild.Reihenfolge++;
bildToSwapReihenfolgeWith.Reihenfolge--;
RaisePropertyChanged(nameof(this.Bilder));
}
}
The order gets updated correctly, but unfortunately, the view doesn't reflect the changes... only after closing and reopening the view, the entries in the DataGrid are in the correct order.
- What am I doing wrong here?
- How can I make the DataGrid update, when changing the order?
Thanks in advance