我在wpf中需要一个可拖动的弹出窗口控件,并且想知道你们中的任何人是否可以帮助我......我确实看到了以下帖子:
但这不应该如何运作......?当我点击并拖动它总是重置到一个特定的点,而且评论者说这不是一个有效的方法......? 有没有人有其他选择?
谢谢!
答案 0 :(得分:15)
我们可以编写一个行为来使任何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>
以下是允许我们拖动Popup
:
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();
};
}
}
如果您不熟悉行为,请安装Expression Blend 4 SDK并添加此命名空间:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
并将System.Windows.Interactivity
添加到您的项目中。
答案 1 :(得分:0)
您可以使用自定义边框布局打开子窗口。然后添加一个启用拖动的MouseDown处理程序:
<Window
WindowStyle="None"
ShowInTaskbar="False"
ResizeMode="NoResize"
SizeToContent="Height"
MouseDown="Window_MouseDown">
...
</Window>
在代码背后:
private void Window_MouseDown(Object sender, MouseButtonEventArgs e)
{
this.DragMove();
}