Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF always on top only for parent

Tags:

windows

wpf

I need my window to be always on top but just for his parent.

Is it possible to make a window always on top just for the parent ?

like image 801
Chen Kinnrot Avatar asked Jul 31 '11 11:07

Chen Kinnrot


2 Answers

I know this is a old question but the problem of using Window.Show() is that if the window lost the focus then the window is placed below. For some applications you need to have a child window an also be able to interact with the other windows. To achieve a effect that the child windows only be hidden when the main window is hidden you need to do:

    PopUpWindow PopUp = new PopUpWindow()
    {
        WindowStartupLocation = WindowStartupLocation.Manual,
        Left = 0,
        Top = 0,                
        Topmost = true
    };
    PopUp.Show();

The Topmost property is for showing the window above all, but if we change of application that windows remains on top. So we need to change that property when the mainWindow is Activated or Deactivated.

    public void MainWindow_Activated(object sender, EventArgs e)
    {
        if (PopUp != null)
            PopUp.Topmost = true;
    }
    public void MainWindow_Deactivated(object sender, EventArgs e)
    {
        if (PopUp != null)
            PopUp.Topmost = false;
    }

This approach is done by triggers on the MainWindow and the events on the ViewModel so its a MVVM valid approach, but also you can use events on the code behind.

And in the MainWindow you need to put:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"


<i:Interaction.Triggers>
    <i:EventTrigger EventName="Activated">
        <ei:CallMethodAction TargetObject="{Binding}" MethodName="MainWindow_Activated"/>
    </i:EventTrigger>
    <i:EventTrigger EventName="Deactivated">
        <ei:CallMethodAction TargetObject="{Binding}" MethodName="MainWindow_Deactivated"/>
    </i:EventTrigger>
</i:Interaction.Triggers>
like image 83
Jaime Avatar answered Sep 21 '22 01:09

Jaime


Set the Owner property of your child window, pointing to the opener window. This way it will always be on top of its parent.

SomeWindow childWindow = new SomeWindow();
childWindow.Owner = this;
childWindow.Show();
like image 41
Yiğit Yener Avatar answered Sep 18 '22 01:09

Yiğit Yener