Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF TreeView restores its focus after double click

Tags:

c#

wpf

treeview

I have a WPF TreeView with XAML shown below:

<TreeView x:Name="twElements">
            <TreeView.Resources>
                <v8r:IconTypeConverter x:Key="IconConverter"/>
            </TreeView.Resources>

            <TreeView.ItemContainerStyle>
                <Style TargetType="{x:Type TreeViewItem}">
                    <EventSetter Event="MouseDoubleClick" Handler="twElements_MouseDoubleClick" />
                </Style>
            </TreeView.ItemContainerStyle>

            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding ChildItems}">
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{Binding Icon, Converter={StaticResource IconConverter}}"/>
                        <TextBlock Text="{Binding Text}" Margin="3,0,0,0"/>
                    </StackPanel>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>

The task is to open some form after double click on a child item.

code-behind for DoubleClick event:

private void twElements_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (e.Source is TreeViewItem && ((TreeViewItem)e.Source).IsSelected)
            {
                e.Handled = true;

                var twi = (TreeViewItem)e.Source;

                var Editable = twi.Header as IEditable;
                if (Editable != null)
                {

                    Window Editor = Editable.GetEditor();
                    Editor.Show(); // Editor is a WPF.Window

                }

            }

}

The problem: After desired window is opened, form with a treeview activates itself, making new window to go background. How to make new window to remain active?

like image 972
Evil Beaver Avatar asked Dec 27 '12 13:12

Evil Beaver


1 Answers

You probably need to let WPF finish the job of handling the current mouse click event(s) before you open the new Window. Let the new window be the next UI job by adding it to the current Dispatcher's queue like this:

(...)

//Editor.Show();
Action showAction = () => Editor.Show();
this.Dispatcher.BeginInvoke(showAction);
like image 72
Sphinxxx Avatar answered Sep 29 '22 17:09

Sphinxxx