How to bring window to front with wpf and using mvvm

前端 未结 3 1676
野的像风
野的像风 2021-01-18 06:46

I have a window that essentially runs a timer. When the timer hits 0 I want to bring the window to the front so that it is visible and not hidden behind some other applica

3条回答
  •  -上瘾入骨i
    2021-01-18 07:39

    A "purist" MVVM solution is to use a behavior. Below is a behavior for a Window with an Activated property. Setting the property to true will activate the window (and restore it if it is minimized):

    public class ActivateBehavior : Behavior {
    
      Boolean isActivated;
    
      public static readonly DependencyProperty ActivatedProperty =
        DependencyProperty.Register(
          "Activated",
          typeof(Boolean),
          typeof(ActivateBehavior),
          new PropertyMetadata(OnActivatedChanged)
        );
    
      public Boolean Activated {
        get { return (Boolean) GetValue(ActivatedProperty); }
        set { SetValue(ActivatedProperty, value); }
      }
    
      static void OnActivatedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) {
        var behavior = (ActivateBehavior) dependencyObject;
        if (!behavior.Activated || behavior.isActivated)
          return;
        // The Activated property is set to true but the Activated event (tracked by the
        // isActivated field) hasn't been fired. Go ahead and activate the window.
        if (behavior.AssociatedObject.WindowState == WindowState.Minimized)
          behavior.AssociatedObject.WindowState = WindowState.Normal;
        behavior.AssociatedObject.Activate();
      }
    
      protected override void OnAttached() {
        AssociatedObject.Activated += OnActivated;
        AssociatedObject.Deactivated += OnDeactivated;
      }
    
      protected override void OnDetaching() {
        AssociatedObject.Activated -= OnActivated;
        AssociatedObject.Deactivated -= OnDeactivated;
      }
    
      void OnActivated(Object sender, EventArgs eventArgs) {
        this.isActivated = true;
        Activated = true;
      }
    
      void OnDeactivated(Object sender, EventArgs eventArgs) {
        this.isActivated = false;
        Activated = false;
      }
    
    }
    

    The behavior requires a reference to System.Windows.Interactivity.dll. Fortunately, this is now available on NuGet in the Blend.Interactivity.Wpf package.

    The behavior is attached to a Window in XAML like this:

    
      
        
      
    

    The view-model should expose a boolean Activated property. Setting this property to true will activate the window (unless it is already activated). As an added bonus it will also restore a minimized window.

提交回复
热议问题