简体   繁体   中英

Draggable Borderless Window and Button click handler in WPF

The Button handler doesnt work because of the DragMove call in Window mouse down handler. Is there any way how to let the events bubbling? I tried set up e.Handled to false, but it does not work.

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

    private void Window_MouseDown(object sender, MouseButtonEventArgs e)
    {    
        this.DragMove();
        e.Handled = false;
    }   

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        System.Console.WriteLine("zde");
    }
}

The Button handler doesnt work because of the DragMove call

Actually, it doesn't work, because the first fires is an event at the Button.Click , and when it works, it conflicts with the events like: MouseLeftButtonDown, MouseUp, MouseDown and for routed events e.Handled property is false by default.

To make this work, you need to define an PreviewMouseDown event, but it's a Tunnel event, this means that it will go down of the VisualTree hierarchy, therefore it is triggered before the Bubble events.

Example:

XAML

<Window x:Class="MyProject.MainWindow"
        ...
        PreviewMouseDown="Window_PreviewMouseDown" ... />

Code-behind

private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == MouseButton.Left)
        this.DragMove();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM