How to make a WPF window be on top of all other windows of my app (not system wide)?

后端 未结 19 3030
南笙
南笙 2020-12-14 05:42

I want my window to be on top of all other windows in my application only. If I set the TopMost property of a window, it becomes on top of all windows of al

19条回答
  •  一个人的身影
    2020-12-14 05:48

    I just ran into the same problem and found trouble setting the owner using MVVM without causing the app to crash in production. I have a Window Manager View Model that includes a command to open a window using the uri of the window - and I wasn't able to set the owner to App.MainWindow without the app crashing.

    So - Instead of setting the owner, I bound the TopMost property of the window to a property in my Window Manager View model which indicates whether the application is currently active. If the application is active, the window is on top as I would like. If it is not active, other windows can cover it.

    Here is what I added to my View Model:

     public class WindowManagerVM : GalaSoft.MvvmLight.ViewModelBase
        {
            public WindowManagerVM()
            {
                App.Current.Activated += (s, e) => IsAppActive = true;
                App.Current.Deactivated += (s, e) => IsAppActive = false;
            }
    
            private bool _isAppActive = true;
            public bool IsAppActive
            {
                get => _isAppActive;
                set
                {
                    if (_isAppActive != value)
                    {
                        _isAppActive = value;
                        RaisePropertyChanged(() => IsAppActive);
                    }
                }
            }
        }
    

    Here is the XAML that implements it (I use MVVM light with a ViewModelLocator as a static resource in my app called Locator):

    
    

提交回复
热议问题