4
votes

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

2

2 Answers

3
votes

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

0
votes

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;
}