Question

I have an application with a treeview and a textbox:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="550" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <TreeView Width="500" Height="500" Name="TestTreeView">

        </TreeView>
        <TextBox Grid.Row="1"></TextBox>
    </Grid>
</Window>

In the constructor for the application I generate 1000 items, each with 1 sub-item and add it to the TreeView:

public MainWindow()
{
    InitializeComponent();

    for (int i = 0; i < 1000; i++)
    {
        TreeViewItem item = new TreeViewItem();
        item.Header = "Hey there " + i.ToString();
        TreeViewItem subItem = new TreeViewItem();
        subItem.Header = "Hi there";
        item.Items.Add(subItem);
        TestTreeView.Items.Add(item);
    }
}

In my scenario, I select the second item of the TreeView, then click into the TextBox to take focus away from the TreeView. I then scroll down the TreeView with my mouse, bringing the selected item out of the viewport. I then expand another item without selecting it. My expected result is that my scroll stays in its current position, however instead it scrolls the selected item back into view, causing me to lose the item I was expanding.

This doesn't occur if the TreeView already has the focus. If I were to select an item, then scroll down and expand another item this behaviour of jumping back to the selected item won't happen.

Is this normal behaviour? If I perform these same selection steps in the Solution Explorer of Visual Studio, for instance, I don't get this kind of behaviour. Is there some way to tell it not to scroll back to the selected item like this?

I understand that I can simply set the e.Handled of the RequestBringIntoView to true, however the sample I'm giving is just a simple explanation of my problem. This is an example of an issue with a TreeView I'm using in a much bigger application where I do want the item brought into view under certain conditions.

Was it helpful?

Solution

The issue is related to the logical scope concept called FocusScope.

What you want is to set IsFocusScope for your TreeView to true:

<TreeView Width="500" Height="500" Name="TestTreeView" FocusManager.IsFocusScope="true">
</TreeView>

Here is an article about it http://www.codeproject.com/Articles/38507/Using-the-WPF-FocusScope

Here is the .net 4.5 doc for it: http://msdn.microsoft.com/en-us/library/aa969768.aspx As it explains it better than I can and which may be more up to date then the codeproject article

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top