Reputation: 53
I want a list view to sort based on an Object its bounded to
<ListView x:Name="ListView1" Grid.Row="2" Grid.Column="2" VirtualizingStackPanel.IsVirtualizing="True" ScrollViewer.CanContentScroll="False" ItemsSource="{Binding Path=CurrentProductsImages}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="0,0,2,0" >
<Image Source="{Binding Path=Data, Converter={StaticResource ImageSourceConverter}}" RenderOptions.BitmapScalingMode="Fant" Height="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView} },Path=ActualHeight, Converter={StaticResource HeightMinusConverter}}" />
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
So the Binded Item CurrentProductsImages has a variable called "DisplayOrder" I want to order the Listview off this value but can't find a way. Most vertical methods of sorting use a gridview but as mines stacked horizontally i cant get it to work?
I can sort the object prior to binding but i wanted it to be more on the WPF side. any ideas? Many thanks
Upvotes: 0
Views: 240
Reputation: 12276
The xaml way of sorting would be to use a collectionviewsource. That has sortdescriptions.
<CollectionViewSource x:Key="SortedItems" Source="{Binding UnsortedItems}" >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Blaa" />
<scm:SortDescription PropertyName="Blaa2" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
The problem being you can't bind those sortdescriptions.
You could potentially do something with a behaviour or custom frameworkelement. That would allow you to write a bunch of code and kind of make this work in the UI. It'd be more complicated than doing the sorting in the viewmodel though.
I suggest you instead add a collectionview to your viewmodel and handle the sorting there in code. You can define a custom icomparer to use or just clear and add sortdescriptions.
Or sort using Linq if that is better suited to your requirement / skillset.
Examples of sorting (and doing other stuff ) with collections:
https://social.technet.microsoft.com/wiki/contents/articles/26673.wpf-collectionview-tips.aspx
There's a working sample linked.
Esentially, with an observablecollection of People, this is bound using:
public CollectionView PeopleView {get; set;}
Set up:
CollectionViewSource cvs = new CollectionViewSource();
cvs.Source = People;
PeopleView = (CollectionView)cvs.View;
Sorted:
PeopleView.SortDescriptions.Clear();
PeopleView.SortDescriptions.Add(new SortDescription("OrganizationLevel", ListSortDirection.Ascending));
PeopleView.SortDescriptions.Add(new SortDescription("LastName", ListSortDirection.Ascending));
PeopleView.SortDescriptions.Add(new SortDescription("FirstName", ListSortDirection.Ascending));
Upvotes: 1