7
votes

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?

2

2 Answers

10
votes

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);
-1
votes

in constructor of new form set

this.Focus();

Also, does your new form should be Modal window? if yes use Editor.ShowDialog() instead of Editor.Show(); It will automatically solve issue with focus