How do you programatically select values in TreeView that uses data binding in WPF?
<p>I want my program to automatically select the most recently created object when it's added to the list. Here's the current code which doesn't work:</p>

<pre><code>    public static void CreateResourceTree(TreeView selector,IEnumerable&lt;Resource&gt; resources,Resource onRefresh=null)
    {
        ActiveResources.Clear();
        ActiveResources.AddRange(resources.OrderByDescending(x=&gt;x.FetchMeta("Priority").IntValue)
        .ThenBy(x=&gt;x.Label)
        .ToList());
        selector.Items.Refresh();
        selector.SelectedItem=onRefresh;
    }
</code></pre>

<p>The code is meant to set the value to the value of <code>onRefresh</code> Unfortunately, SelectedItem as ReadOnly, which results in an error.</p>

<p>When I Googled the issue, the only solution I found to programatically selecting an item is to use the "IsSelected" property on a TreeViewItem, but since this is data-bound, it doesn't use or recognize TreeViewItem objects.</p>

<p>Here is the XAML code, in case it's needed:</p>

<pre><code>    &lt;TreeView ItemsSource="{Binding ResourceList}" Grid.Column="0" Grid.Row="3" x:Name="ResourcesTree" SelectedItemChanged="ResourcesTree_OnSelectedItemChanged" Margin="0,4,0,0"&gt;
        &lt;TreeView.ItemTemplate&gt;
            &lt;HierarchicalDataTemplate DataType="{x:Type xmlclass:Resource}" ItemsSource="{Binding Children}"&gt;
                &lt;ContentPresenter Content="{Binding Output}" /&gt;
            &lt;/HierarchicalDataTemplate&gt;
        &lt;/TreeView.ItemTemplate&gt;
    &lt;/TreeView&gt;
</code></pre>