Mike Borozdin
Mike Borozdin

Reputation: 1188

How to Focus an Element in a WPF TreeView If Elements Come From ItemSource?

I can also paraphrase the question and ask how I can get a TreeViewItem out of a Model object in TreeView.Items?

I follow this tutorial and instead of TreeViewItems in the TreeView.Items collection I have objects of that model class.

However, I need to focus certain TreeView elements based on some other event. If TreeView.Items contained TreeViewItems I'd easily found a needed one and used its Focus() method. But since I'm using binding now I don't know how to do that.

Of course, I can populate a TreeView programmatically by adding TreeViewItems objects, however I tried to avoid it and follow a more WPF-way of doing things with binding.

Upvotes: 3

Views: 9591

Answers (3)

Bruno
Bruno

Reputation: 1974

You might want to use ItemContainerGenerator.ContainerFromItem

Find a post here : http://bea.stollnitz.com/blog/?p=7

And a small sample on how to use it :

XAML

<TreeView x:Name="tv" ItemsSource="{Binding MyDataList}" SelectedItemChanged="tv_SelectedItemChanged">
    <TreeView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding BusinessProperty}"/>
        </DataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

code behind :

private void tv_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    var tvItem = tv.ItemContainerGenerator.ContainerFromItem(((TreeView)sender).SelectedItem);
}

and then do whatever you want with your treeview item :)

Upvotes: 0

Ben
Ben

Reputation: 1043

  <Style TargetType="TreeViewItem" BasedOn="{StaticResource {x:Type TreeViewItem}}">
    <Setter Property="IsSelected" Value="{Binding IsSelectedInEditor, Mode=TwoWay}" />
  </Style>

This is my style for a TreeViewItem where i bound the IsSelected property to the Model object's IsSelectedInEditor property. Maybe it's not the best way to do this, but i found it easier than other solutions and it's worked out of the box. So after this setup you just need to find your object in the TreeView.Items and set its IsSelectedInEditor(or whatever name you choose) property to true.

Upvotes: 1

brunnerh
brunnerh

Reputation: 184376

TreeViewItem tvItem = (TreeViewItem)treeView
                          .ItemContainerGenerator
                          .ContainerFromItem(item);
tvItem.Focus();

Upvotes: 8

Related Questions