title: How do I sort a WPF TreeView using the HierarchicalDataTemplate for EntityCollection objects?
body: <p>My <em>Webpage</em> is an Entity Framework entity. These are bound to a WPF TreeView. I want to order all the <em>Webpages</em> shown in the TreeView on the <em>Sort</em> property.</p>
  
  <h2>Code</h2>
  
  <p><strong>EDMX</strong></p>
  
  <p><img src="https://i.stack.imgur.com/8yNLh.gif" alt="Entity Framework EDMX entity"></p>
  
  <p>Its <em>Subordinates</em> property returns a collection of zero or more <em>Webpages</em>.</p>
  
  <p><strong>XAML</strong></p>
  
  <pre><code>&lt;TreeView Name="TreeViewWebpages"&gt;
      &lt;TreeView.Resources&gt;
          &lt;HierarchicalDataTemplate DataType="{x:Type local:Webpage}"
                                    ItemsSource="{Binding Subordinates}"&gt;
              &lt;TextBlock Text="{Binding Path=Title}" /&gt;
          &lt;/HierarchicalDataTemplate&gt;
      &lt;/TreeView.Resources&gt;
  &lt;/TreeView&gt;
  </code></pre>
  
  <p><strong>C#</strong></p>
  
  <pre><code>TreeViewWebpages.ItemsSource = from Webpage root in db.Webpages.Include("Subordinates")
                                 where root.Dominant == null
                                 select root;
  </code></pre>
  
  <h2>Result</h2>
  
  <p><em>Webpages</em> are unordered within the TreeView.</p>
  
  <h2>Problem</h2>
  
  <p>How do I change this to order all the <em>Webpages</em> shown in the TreeView on the <em>Sort</em> property?</p>
  
  <hr>
  
  <h1>Update</h1>
  
  <p>This ValueConverter seems to work (Thank you @KP Adrian and @IVerzin). Is there a better way?</p>
  
  <p><strong>XAML</strong></p>
  
  <pre><code>ItemsSource="{Binding Path=Subordinates, Converter={local:SortConverter}}"
  </code></pre>
  
  <p><strong>C#</strong></p>
  
  <pre><code>[ValueConversion(typeof(EntityCollection&lt;Webpage&gt;), typeof(EntityCollection&lt;Webpage&gt;))]
  public class SortConverter : MarkupExtension, IValueConverter
  {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
          return ((EntityCollection&lt;Webpage&gt;)value).OrderBy(o =&gt; o.Sort);
      }
  
      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
          return null;
      }
  
      public override object ProvideValue(IServiceProvider serviceProvider)
      {
          return this;
      }
  }
  </code></pre>