I've been looking for a solution for my problem since yesterday. Im building a problem with MVVM pattern. I got two usercontrol, which are both containing a listbox.
The first usercontrol is called the SearchView which contains a listbox of project names, which the user can select and save to the applications local db.
When the selected projects are added a event is fired which notify the 2nd usercontrol which is named "ProjectView". This usercontrol simply shows which projects are saved locally. Seen at the picture below.
The problem is that i want to be able sort the listbox ascending by name in the projectview. So that if the user first add "Test Project 2" and afterwords add "Test Project 1" the "Test Project 1" is shown in the top of the listbox.
I have tried to use ICollectionView and ListCollectionView but im very really confused at the moment.
So now my Code looks like this, in the ProjectViewModel which needs to sort the listbox:
public ProjectViewModel() {
this.collectionView = CollectionViewSource.GetDefaultView(this.Projects);
}
private ObservableCollection<ProjectWrapper> _project = new ObservableCollection<ProjectWrapper>();
public ObservableCollection<ProjectWrapper> Projects
{
get { return _project; }
set
{
_project = value;
OnPropertyChanged("Projects");
}
}
XAML code:
<UserControl.Resources>
<CollectionViewSource x:Key="cvs" Source="{Binding Path=Projects}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="ProjectWrapper.Project.Name" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</UserControl.Resources>
<ListBox Name="ProjectsList" ItemsSource="{Binding Source={StaticResource cvs}}" SelectedItem="{Binding Path=SelectedProject}" HorizontalContentAlignment="Stretch" BorderThickness="0" Grid.Row="1" Grid.RowSpan="3" Margin="0,0.4,-0.2,27.8">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel>
<TextBlock Text="{Binding Path=ProjectModel.Name}" HorizontalAlignment="Left" VerticalAlignment="Center" Padding="3,2,0,0" />
<CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Right" VerticalAlignment="Center" Padding="0,2,5,0" Margin="0,2.5,0,0" />
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Thanks in advance
call this when you adding element to the Projects
list
Projects = new ObservableCollection<ProjectWrapper>(Projects.OrderBy(x => x.Name));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With