WPF keeping a TreeView list sorted
I have a node on a TreeView that I populate manually and want to keep sorted. Thro开发者_开发知识库ugh 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.
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
精彩评论