Search code examples
c#.netwpfwindow

WPF Get sender's window


as the title says I'm looking for a way to get the Window object the sender is in.

In my situation I have a window in which there is only one button:

<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>

By clicking the button, it generates a new window without borders and a red rectangle inside it:

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();
        }
    }
}

My idea was to capture the MouseDown event on the rectangle to move the window (using DragMove()), unfortunately I have no idea how to get the Window object on which the rectangle that invoked the event is located, any idea to do it?.


Solution

  • You can use MouseDown event after new Rectangle and find Window through Parent property like this:

    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
        }
    
    }