Hi I created this small example, and I would like to expand it to support Sorting.
public class Country
{
public string Name { get; set; }
public int SortOrder { get; set; }
}
My xaml:
<TreeView Name="CountryTreeView" ItemsSource="{Binding}">
<TreeView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
And the code-behind:
readonly ObservableCollection<Country> Countries;
public MainWindow()
{
InitializeComponent();
Countries = new ObservableCollection<Country>
{
new Country{Name = "Denmark", SortOrder = 0},
new Country{Name = "Norway", SortOrder = 1},
new Country{Name = "Sweden", SortOrder = 2},
new Country{Name = "Iceland", SortOrder = 3},
new Country{Name = "Greenland", SortOrder = 4},
};
CountryTreeView.DataContext = Countries;
}
I would like to make it possible for the Treeview to Sort the Countries depending on the SortOrder value.
It needs to be able to do this on the fly.
So if I for example change SortOrder = 10 for Name = “Denmark” the TreeView would automatically reflect this.
I don’t think there is a default sort for TreeViews. You can either sort the items prior to entering them into the collection, or overwrite the ObservableCollection to include a Sort method.
I overwrite it in one of my projects:
You would then sort it by calling something like
I like overwriting it because it let me add additional functionality to it as well such as
IndexOforAddRange/RemoveRange