Search code examples
c#wpftopmost

Getting information if Topmost property is changed


I have a class, deriving from Window, in which I want to be notified when the Topmost property is changed.

I tried to override setter, but it's not marked as virtual. Changing metadata connected with this property made it not working (nothing happens after setting topmost true). Also WPF does not provide event connected with this property. I was thinking about overriding Topmost property, but I use it to data binding, so it must stay DependencyProperty.

Is there any way to get that notification?


Solution

  • I try this and it seems like it work fine for me.

    public partial class MainWindow : Window
    {
        static MainWindow()
        {
            Window.TopmostProperty.OverrideMetadata(typeof(MainWindow),
                new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None,
                    new PropertyChangedCallback(OnTopMostChanged)));
        }
        public event EventHandler TopmostChanged;
        private static void OnTopMostChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            MainWindow mv = (MainWindow)d;
            if (mv.TopmostChanged != null)
                mv.TopmostChanged(mv, EventArgs.Empty);
        }
    
        private void ChangeTopmostBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Topmost = !this.Topmost;
        }
        ...
    }
    

    When i click on my ChangeTopmost button, i get inside OnTopMostChanged method. So if you do the same and have anyone registered to TopmostChanged event, it will get the event.