Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a listbox when a button gets clicked using MVVM

Tags:

c#

mvvm

wpf

xaml

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.

enter image description here

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.

enter image description here

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

like image 431
RooKie- Avatar asked May 03 '13 10:05

RooKie-


1 Answers

call this when you adding element to the Projects list

Projects = new ObservableCollection<ProjectWrapper>(Projects.OrderBy(x => x.Name));
like image 91
Chamika Sandamal Avatar answered Nov 08 '22 04:11

Chamika Sandamal