2
我使用Stack Overflow上的代码来使用附加的行为来使WPF弹出窗口可拖动。此代码和行为按预期工作。弹出窗口将保持拖动位置,直到用户再次移动它。关闭后,如何将可拖动的wpf弹出框设置为原始位置?
我现在想要做的是让弹出窗口出现在原来的放置目标位置,一旦它关闭并重新打开。我如何完成这项任务?
原帖:由Rick Sladkey书面A draggable popup control in wpf
答案代码:https://stackoverflow.com/a/4784977/1286413
下面是弹出的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();
};
}
}
在此先感谢帮助!
提供的代码有一个修改:我将AssociatedObject.Closed更改为AssociatedObject.Loaded。由于PlacementTarget是在创建弹出窗口时设置的,因此我需要定位此事件,以便弹出窗口知道它开始的位置。我编辑了答案以反映这一变化。非常感谢您的帮助。 –