title: Data binding to SelectedItem in a WPF Treeview
body: <p>How can I retrieve the item that is selected in a WPF-treeview? I want to do this in XAML, because I want to bind it.</p>
  
  <p>You might think that it is <code>SelectedItem</code> but apparently that <s>does not exist</s> is readonly and therefore unusable.</p>
  
  <p>This is what I want to do:</p>
  
  <pre><code>&lt;TreeView ItemsSource="{Binding Path=Model.Clusters}" 
              ItemTemplate="{StaticResource ClusterTemplate}"
              SelectedItem="{Binding Path=Model.SelectedCluster}" /&gt;
  </code></pre>
  
  <p>I want to bind the <code>SelectedItem</code> to a property on my Model.</p>
  
  <p>But this gives me the error:</p>
  
  <blockquote>
    <p>'SelectedItem' property is read-only and cannot be set from markup.</p>
  </blockquote>
  
  <p><strong>Edit:</strong>
  Ok, this is the way that I solved this:</p>
  
  <pre><code>&lt;TreeView
            ItemsSource="{Binding Path=Model.Clusters}" 
            ItemTemplate="{StaticResource HoofdCLusterTemplate}"
            SelectedItemChanged="TreeView_OnSelectedItemChanged" /&gt;
  </code></pre>
  
  <p>and in the codebehindfile of my xaml:</p>
  
  <pre><code>private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs&lt;object&gt; e)
  {
      Model.SelectedCluster = (Cluster)e.NewValue;
  }
  </code></pre>