我已经找到了一个解决方案(如何使用户控件在屏幕上像窗口一样可拖动),但它不像我想要的那样工作。在这个解决方案中,只有UserControl的内容是可拖动的,但是我用ShowDialog方法打开我的UserDialog,所以UserControl是一个单独的对话框(https://prismlibrary.com/docs/wpf/dialog-service.html)。
是否有任何等价于UserControl的DragMove()方法?
我不知道我是否理解正确,但是你想要一个行为,当一个用户控件被拖动时,你想要父窗口被拖动。这里是:
public class DragParentWindowBehavior : Behavior<UserControl>
{
private Window parentWindow;
protected override void OnAttached()
{
AssociatedObject.Loaded += AssociatedObject_Loaded;
AssociatedObject.Unloaded += AssociatedObject_Unloaded;
AssociatedObject.PreviewMouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
}
private void AssociatedObject_Unloaded(object sender, RoutedEventArgs e)
{
parentWindow = null;
}
private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
//We get the parent window here. because the behavior is attached to the view way before it is shown.
parentWindow = Window.GetWindow(AssociatedObject);
}
private void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
parentWindow?.DragMove();
}
protected override void OnDetaching()
{
AssociatedObject.PreviewMouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;
AssociatedObject.Loaded -= AssociatedObject_Loaded;
AssociatedObject.Unloaded -= AssociatedObject_Unloaded;
parentWindow = null;
}
}
在XAML中的用法:
<UserControl x:Class="Prism1.Modules.ModuleName.Views.DraggableControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Prism1.Modules.ModuleName.Views"
xmlns:Behaviors="http://schemas.microsoft.com/xaml/behaviors"
xmlns:mvvm="clr-namespace:Prism1.Core.Mvvm;assembly=Prism1.Core"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Behaviors:Interaction.Behaviors>
<mvvm:DragParentWindowBehavior></mvvm:DragParentWindowBehavior>
</Behaviors:Interaction.Behaviors>
<Grid x:Name="LayoutRoot" Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Message}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0" TextWrapping="Wrap" />
<Button Command="{Binding CloseDialogCommand}" CommandParameter="true" Content="OK" Width="75" Height="25" HorizontalAlignment="Right" Margin="0,10,0,0" Grid.Row="1" IsDefault="True" />
</Grid>
</UserControl>