Parent TreeView Item ghost selected event!

孤街醉人 提交于 2019-12-10 17:35:50

问题


I have a TreeView that launches a new window when each of its TreeViewItems Selected event is raised.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1"
    Height="300"
    Width="300">
<Grid>
    <TreeView  Name="treeView1">
        <TreeViewItem Header="Root">
            <TreeViewItem Header="Parent" Selected="ParentTreeViewItem_Selected">
                <TreeViewItem Header="Child" Selected="TreeViewItem_Selected" ></TreeViewItem>
            </TreeViewItem>
        </TreeViewItem>
    </TreeView>
</Grid>
</Window>

Code Behind

namespace WpfApplication1

{ public partial class Window1 : Window { public Window1() { InitializeComponent(); }

    private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
    {
        Window w = new Window();
        w.Show();
        e.Handled = true;
    }

    private void ParentTreeViewItem_Selected(object sender, RoutedEventArgs e)
    {

    }
}

}

When I click on the child node the new window is launched as expected. However imediatly afterwords its parents Selected eventis fired stealing focus from the new window, and marking the parent node as the current selection!

My expectation was that the newly launched window would have focus, and the node that was clicked would turn gray indicating to the users his/hers selection. Does anyone have any idea of why this happens and how I can prevent it?

Thanks, Brette


回答1:


Thought I would post the answer. I finally found a way around this. Setting w.Owner = this; has no effect. Turns out launching a new window on the Selected event of a TreeViewItem causes some focus issues. I have not found out what the root cause is by executing this on the Dispatcher seems to correct it. See Below

    private void ChildTreeViewItem_Selected(object sender, RoutedEventArgs e)
    {
        Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => new Window().Show()));
    }

Hope this saves someone else some time.

Brette




回答2:


Add:

w.Owner = this      

Example:

private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
{
    Window w = new Window();
    w.Owner = this;
    w.Show();
    e.Handled = true;
}


来源:https://stackoverflow.com/questions/1314116/parent-treeview-item-ghost-selected-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!