devlights
5/25/2015 - 3:04 PM

WPFFollowPopup (PlacementTargetに追随するポップアップ)

WPFFollowPopup (PlacementTargetに追随するポップアップ)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Interactivity;

namespace DraggablePopup
{
  public class FollowPopupBehavior : Behavior<Popup>
  {
    protected override void OnAttached()
    {
      base.OnAttached();

      var w = Window.GetWindow(AssociatedObject);
      w.LocationChanged += w_LocationChanged;
    }

    protected override void OnDetaching()
    {
      var w = Window.GetWindow(AssociatedObject);
      w.LocationChanged -= w_LocationChanged;

      base.OnDetaching();
    }

    void w_LocationChanged(object sender, EventArgs e)
    {
      var offset = AssociatedObject.HorizontalOffset;
      AssociatedObject.HorizontalOffset = offset + 1;
      AssociatedObject.HorizontalOffset = offset;
    }
  }
}