This should be no problem with a value converter.
Simple example (new WPF project, DataContext of MainWindow set to Application.Current):
public class Node
{
public Node(int ordinal)
{
this.Ordinal = ordinal;
this.Children = new List<Node>();
}
public int Ordinal { get; set; }
public List<Node> Children { get; private set; }
}
public class NodeSortConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
List<Node> nodes = value as List<Node>;
if (nodes != null)
{
List<Node> sorted = new List<Node>(nodes);
sorted.Sort(new Comparison<Node>((x, y) => x.Ordinal.CompareTo(y.Ordinal)));
return sorted;
}
else
throw new ArgumentException();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
<Window.Resources>
<local:NodeSortConverter x:Key="nodeSorter" />
</Window.Resources>
<Grid>
<TreeView ItemsSource="{Binding Nodes}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children, Converter={StaticResource nodeSorter}}">
<Border Margin="3">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Ordinal}" />
</StackPanel>
</Border>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
public partial class App : Application
{
private Random _rand = new Random((int)DateTime.Now.Ticks);
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Nodes = new List<Node>();
Nodes.Add(CreateNodeTree(new Node(_rand.Next()), 3, 5));
}
private Node CreateNodeTree(Node root, int depth, int childCount)
{
for (int i = 0; i < childCount; i++)
{
Node child = new Node(_rand.Next());
root.Children.Add(child);
if (depth > 0)
CreateNodeTree(child, depth - 1, childCount);
}
return root;
}
public List<Node> Nodes { get; set; }
}