using System;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Interactivity;
namespace Common.Wpf.Validation
{
///
/// Defines the reposition behavior of a control when the window to which it is attached is moved or resized.
///
///
/// This solution was influenced by the answers provided by NathanAW and
/// Jason to
/// this question.
///
public class RepositionPopupBehavior : Behavior
{
#region Protected Methods
///
/// Called after the behavior is attached to an .
///
protected override void OnAttached()
{
base.OnAttached();
var window = Window.GetWindow(AssociatedObject.PlacementTarget);
if (window == null) { return; }
window.LocationChanged += OnLocationChanged;
window.SizeChanged += OnSizeChanged;
AssociatedObject.Loaded += AssociatedObject_Loaded;
}
void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
//AssociatedObject.HorizontalOffset = 7;
//AssociatedObject.VerticalOffset = -AssociatedObject.Height;
}
///
/// Called when the behavior is being detached from its , but before it has actually occurred.
///
protected override void OnDetaching()
{
base.OnDetaching();
var window = Window.GetWindow(AssociatedObject.PlacementTarget);
if (window == null) { return; }
window.LocationChanged -= OnLocationChanged;
window.SizeChanged -= OnSizeChanged;
AssociatedObject.Loaded -= AssociatedObject_Loaded;
}
#endregion Protected Methods
#region Private Methods
///
/// Handles the routed event which occurs when the window's location changes.
///
///
/// The source of the event.
///
///
/// An object that contains the event data.
///
private void OnLocationChanged(object sender, EventArgs e)
{
var offset = AssociatedObject.HorizontalOffset;
AssociatedObject.HorizontalOffset = offset + 1;
AssociatedObject.HorizontalOffset = offset;
}
///
/// Handles the routed event which occurs when either then or the
/// properties change value.
///
///
/// The source of the event.
///
///
/// An object that contains the event data.
///
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
var offset = AssociatedObject.HorizontalOffset;
AssociatedObject.HorizontalOffset = offset + 1;
AssociatedObject.HorizontalOffset = offset;
}
#endregion Private Methods
}
}