TreeView问题与扩展非选定项目

fla*_*aud 7 wpf treeview expand scroll treeviewitem

我有一个带有树视图和文本框的应用程序:

<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>
Run Code Online (Sandbox Code Playgroud)

在应用程序的构造函数中,我生成1000个项目,每个项目有1个子项目并将其添加到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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的场景中,我选择TreeView的第二项,然后单击进入TextBox以使焦点远离TreeView.然后我用鼠标向下滚动TreeView,将所选项目从视口中移出.然后我扩展另一个项目而不选择它.我的预期结果是我的滚动停留在当前位置,但是它将所选项目滚动到视图中,导致我丢失了我正在扩展的项目.

如果TreeView已经具有焦点,则不会发生这种情况.如果我要选择一个项目,然后向下滚动并展开另一个项目,则不会发生这种跳回所选项目的行为.

这是正常的行为吗?例如,如果我在Visual Studio的解决方案资源管理器中执行这些相同的选择步骤,我就不会遇到这种行为.有没有办法告诉它不要回滚到这样的选定项目?

我知道我可以简单地将RequestBringIntoView的e.Handled设置为true,但是我给出的示例只是对我的问题的一个简单解释.这是我在一个更大的应用程序中使用的TreeView问题的一个例子,我希望在某些条件下将项目带入视图.

Sam*_*uel 5

此问题与称为FocusScope的逻辑范围概念有关。

您想要将TreeView的IsFocusScope设置为true:

<TreeView Width="500" Height="500" Name="TestTreeView" FocusManager.IsFocusScope="true">
</TreeView>
Run Code Online (Sandbox Code Playgroud)

这是关于它的文章http://www.codeproject.com/Articles/38507/Using-the-WPF-FocusScope

这是它的.net 4.5文档:http : //msdn.microsoft.com/zh-cn/library/aa969768.aspx 因为它比我更好地解释了它,所以可能比codeproject文章更新得多了。