我试图通过主窗口拖动第二个窗口,每当我移动第一个窗口时,第二个窗口就会与主窗口一起拖动到主窗口的右侧。
无论我尝试过什么都没有奏效,我尝试过 DragMove() 但它没有移动第二个窗口它只移动了主窗口,我对 C# 和 WPF 没有真正的经验。
答案 0 :(得分:1)
您可以使用以下代码。只计算第一个窗口的最后一个点与其当前位置的差值,并将得到的值加到第二个窗口的位置上,当然这一切都适用于事件LocationChanged
。
MyWindow1.cs
public partial class MyWindow1 : Window
{
MyWindow2 wnd;
Point last = new Point();
public MyWindow1()
{
InitializeComponent();
last.X = this.Left;
last.Y = this.Top;
}
private void Window_LocationChanged(object sender, EventArgs e)
{
if (wnd != null)
{
wnd.Left = (this.Left - last.X) + wnd.Left;
wnd.Top = (this.Top - last.Y) + wnd.Top;
last.X = this.Left;
last.Y = this.Top;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
wnd = new MyWindow2();
wnd.Show();
}
}
MyWindow1.xaml
<Window x:Class="WpfApp1.MyWindow1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MyWindow1" Height="450" Width="800" LocationChanged="Window_LocationChanged">
<StackPanel>
<Button Content="Get Window 2" Width="150" Height="35" VerticalAlignment="Center" Click="Button_Click"></Button>
</StackPanel>
</Window>