sorting elements in a stackpanel WPF

后端 未结 4 1037
春和景丽
春和景丽 2020-12-19 06:35

I have a stackpanel with some usercontrols that are added or removed during runtime. These elements have an index that i assign to them when i new them, I need to keep these

4条回答
  •  抹茶落季
    2020-12-19 07:06

    Why dont you use a ListBox/ItemsSontrol and use CollectionViewSorce/SortDescription on it to get this work done. Adding an elements to the LayOut Panels like stackpanel is not an efficient way to go in WPF apps. StackPanel with vertical orientation is the default for ListBox/ItemsControl,but if you want some different layout you can always override ListBox.ItemsPanel Template

    If you can follow MVVM apporach then it is a matter of specifying a property(in your case it willbe Index) in your ViewModel class and set SortDescription at the listBox level will automatically give you this feature. Instead of adding and removing actual UIElements, you need just to add/remove to the ObservableCollection bind to ListBox.ItemsSource. And specify proper DataTemplate.

    Check this if you arent familiar with CollectionViewSource - http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.sortdescriptions.aspx

    And the code will be more like below.. it is pretty simple.

       
        
           
            
           
         
              
    
      
    

    note:<--xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"-->

提交回复
热议问题