How to select a WPF TreeViewItem from code

I've been breaking for a couple of hours now on how to select an tree view item properly by code. I'm using the ViewModel's "IsSelected" property which is databinded to the TreeViewItem's "IsSelected" property, but I've now realized that it's not enough...

Some googling brought me to this MSDN forum post, and apparently the problem is that only selecting the TreeViewItem causes problems, what you need to do is also focus it, and the simple of doing that (according to the post) is this:

In the XAML subscribe to the "TreeViewItem.Selected" event:
<TreeView TreeViewItem.Selected="TreeViewItem_Selected" />

And in the code-behind handle it like this:
private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
  {
    TreeViewItem item = e.OriginalSource as TreeViewItem;
    if (item != null && !item.IsFocused)
      item.Focus();
  }

Comments

Mehboob said…
Thanks David..Nice and Crisp

Popular posts from this blog

Restart the Windows File Sharing Service to fix weird problems

WPF, ImageSource and Embedded Resources

SharpDevelop dark color scheme