我使用Stack Overflow上的代码使用附加的行为来创建一个可拖动的WPF弹出窗口。此代码和行为按预期工作。弹出窗口将保持在拖动位置,直到用户再次移动它。
我现在要做的是,一旦关闭并重新打开,弹出窗口就会显示在其原始放置目标位置。我该如何完成这项任务?
原帖:A draggable popup control in wpf
答案代码由Rick Sladkey撰写:https://stackoverflow.com/a/4784977/1286413
以下是Popup的XAML:
<Grid>
<StackPanel>
<TextBox x:Name="textBox1" Width="200" Height="20"/>
</StackPanel>
<Popup PlacementTarget="{Binding ElementName=textBox1}" IsOpen="{Binding IsKeyboardFocused, ElementName=textBox1, Mode=OneWay}">
<i:Interaction.Behaviors>
<local:MouseDragPopupBehavior/>
</i:Interaction.Behaviors>
<TextBlock Background="White">
<TextBlock.Text>Sample Popup content.</TextBlock.Text>
</TextBlock>
</Popup>
</Grid>
这是他写的AttachedBehavior:
public class MouseDragPopupBehavior : Behavior<Popup>
{
private bool mouseDown;
private Point oldMousePosition;
protected override void OnAttached()
{
AssociatedObject.MouseLeftButtonDown += (s, e) =>
{
mouseDown = true;
oldMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
AssociatedObject.Child.CaptureMouse();
};
AssociatedObject.MouseMove += (s, e) =>
{
if (!mouseDown) return;
var newMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
var offset = newMousePosition - oldMousePosition;
oldMousePosition = newMousePosition;
AssociatedObject.HorizontalOffset += offset.X;
AssociatedObject.VerticalOffset += offset.Y;
};
AssociatedObject.MouseLeftButtonUp += (s, e) =>
{
mouseDown = false;
AssociatedObject.Child.ReleaseMouseCapture();
};
}
}
提前感谢您的帮助!
答案 0 :(得分:1)
在OnAttached中,将一个处理程序添加到Closed以保存弹出窗口的位置,将另一个处理程序添加到Opened将弹出窗口移回该位置。
public class MouseDragPopupBehavior : Behavior<Popup>
{
private bool mouseDown;
private Point oldMousePosition;
private bool useSavedPosition;
private Point savedPosition;
protected override void OnAttached()
{
AssociatedObject.MouseLeftButtonDown += (s, e) =>
{
mouseDown = true;
oldMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
AssociatedObject.Child.CaptureMouse();
};
AssociatedObject.MouseMove += (s, e) =>
{
if (!mouseDown) return;
var newMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
var offset = newMousePosition - oldMousePosition;
oldMousePosition = newMousePosition;
AssociatedObject.HorizontalOffset += offset.X;
AssociatedObject.VerticalOffset += offset.Y;
};
AssociatedObject.MouseLeftButtonUp += (s, e) =>
{
mouseDown = false;
AssociatedObject.Child.ReleaseMouseCapture();
};
AssociatedObject.Opened += (s, e) =>
{
if (!useSavedPosition) return;
AssociatedObject.HorizontalOffset = savedPosition.X;
AssociatedObject.VerticalOffset = savedPosition.Y;
};
AssociatedObject.Loaded += (s, e) =>
{
savedPosition = new Point(AssociatedObject.HorizontalOffset, AssociatedObject.VerticalOffset);
useSavedPosition = true;
};
}
}