我已经找到了一个解决方案(如何使用户控件像窗口一样可拖动),但它并不是我想要的方式。在这个解决方案中,只有UserControl的内容是可拖动的,但我使用ShowDialog方法打开我的UserDialog,所以UserControl是一个单独的对话框(https://prismlibrary.com/docs/wpf/dialog-service.html)。
是否有任何等效于DragMove()方法的UserControl方法?
我已经找到了一个解决方案(如何使用户控件像窗口一样可拖动),但它并不是我想要的方式。在这个解决方案中,只有UserControl的内容是可拖动的,但我使用ShowDialog方法打开我的UserDialog,所以UserControl是一个单独的对话框(https://prismlibrary.com/docs/wpf/dialog-service.html)。
是否有任何等效于DragMove()方法的UserControl方法?
我不确定是否理解正确,但您想要一种行为,即当用户控件被拖动时,希望父窗口也被拖动。因此,这里是实现:
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>