WPF 获取发件人的 window

WPF Get sender's window

正如标题所说,我正在寻找一种方法来获取 Window object sender 所在的内容。

在我的情况下,我有一个 window,其中只有一个按钮:

<Window x:Class="WpfApp1.MainWindow"
        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="MainWindow" Height="200" Width="200">
    <Grid>
        <Button Click="Button_Click"/>
    </Grid>
</Window>

通过点击按钮,它会生成一个新的 window 没有边框,里面有一个红色矩形:

using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Window window = new Window();
            window.Height = window.Width = 100;
            window.WindowStyle = WindowStyle.None;

            Rectangle rectangle = new Rectangle();
            rectangle.Height = rectangle.Width = 50;
            rectangle.Fill = new SolidColorBrush(Colors.Red);

            Grid grid = new Grid();
            grid.Children.Add(rectangle);

            window.Content = grid;
            window.Show();
        }
    }
}

我的想法是捕获矩形上的 MouseDown 事件来移动 window(使用 DragMove()),不幸的是我不知道如何获得 Window object调用事件的矩形所在的位置,有什么想法吗?

您可以在新的 Rectangle 之后使用 MouseDown 事件并通过父 属性 找到 Window,如下所示:

private void Rectangle_MouseDown(object sender, MouseButtonEventArgs e)
    {
        var rect = sender as Rectangle;
        FrameworkElement framework = rect;
        while (framework != null && (framework as Window)==null && framework.Parent!= null)
        {
            framework = framework.Parent as FrameworkElement;
        }
        if(framework is Window window)
        {
            //here you has found the window
        }

    }