I have a node on a TreeView that I populate manually and want to keep sorted. Through user interaction the headers on the TreeViewItem's may change and they should move to the appropriate spot in the list.
I iterate through a foreach creating numerous TreeViewItem's and adding them to a parent node. It is all of the children that need to be sorted. I then add a SortDescription as follows.
tviParent.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending));
This sorts the intial list, but if I change the header for one of the tree view items after it is displayed the item does not sort again. The header text changes, but the items position in the list remains the same.
Is there something I am missing?
I have tried clearning the list and repopulating it, which will work, however it causes some isues in my program as I have a lot of logic for when the selected item is changed and since one of the tree view items in the list that I am clearing is selected it invokes all of this logic when I clear the list and then again when I programmatically reselect the item after rebuilding the list.
Tree View. Sort Method System. Windows. Forms Sorts the items in TreeView control. This method reapplies the default sort, which is alphabetical by node text, or a custom sort specified by the TreeViewNodeSorter property.
To find a TreeViewItem that contains a specific data object, you must traverse each level of the TreeView. The items in a TreeView can also be virtualized to improve performance. In the case where items might be virtualized, you also must realize a TreeViewItem to check whether it contains the data object.
The TreeView control provides a convenient way to display hierarchical data. If your TreeView is bound to a data source, the SelectedItem property provides a convenient way for you to quickly retrieve the selected data object.
ItemTemplate is used to get or set the date for every TreeViewItem. For now we need to display data in a hierarchical way so in ItemTemplate again we need to HierarchicalDataTemplate class.
The items collection will have to be refreshed upon any change to its property
try the following code after the header edit ....
tviParent.Items.Refresh();
if the code above does not work then try code below after each edit ...
tviParent.Items.SortDescriptions.Clear()
tviParent.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending));
If you set
yourCollectionView.IsLiveSorting = true;
then it will update automatically.
Also to get this to work recusively put this into a converter like here: https://stackoverflow.com/a/5730402/364429
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