WPF mouse event propagated from child window to owner window

25 Views Asked by At

I wrote a little bit of code to describe my problem: When clicking on a control on main window, MouseLeftButtonDown command show a child window as modal. When double clicking in the child window, the MouseLeftButtonUp in the main window is fired. How avoid this without a flag?

MAIN

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

    private void MouseLeftButtonDownCommand(object sender, MouseButtonEventArgs e)
    {
        ChildWindow childWindow = new ChildWindow();
        childWindow.Owner = this;
        childWindow.ShowDialog();
    }

    private void MouseLeftButtonUpCommand(object sender, MouseButtonEventArgs e)
    {
        MessageBox.Show("Event Propagated to main window");
    }
}

MAIN XAML

<Grid>
    <Canvas Background="Transparent" MouseLeftButtonDown="MouseLeftButtonDownCommand" MouseLeftButtonUp="MouseLeftButtonUpCommand">
        
    </Canvas>
</Grid>

MODAL WINDOW

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

    private void LeftDoubleClickCommand(object sender, MouseButtonEventArgs e)
    {
        this.Close();
    }
}

MODAL WINDOW XAML

<Grid>
    <ListView Margin="10" MouseDoubleClick="LeftDoubleClickCommand">
        <ListViewItem Content="Coffie"></ListViewItem>
        <ListViewItem Content="Tea"></ListViewItem>
        <ListViewItem Content="Orange Juice"></ListViewItem>
        <ListViewItem Content="Milk"></ListViewItem>
        <ListViewItem Content="Iced Tea"></ListViewItem>
        <ListViewItem Content="Mango Shake"></ListViewItem>
    </ListView>
</Grid>
1

There are 1 best solutions below

3
mm8 On

Don't close the dialog window until the message loop is empty:

private void LeftDoubleClickCommand(object sender, MouseButtonEventArgs e)
{
    Dispatcher.BeginInvoke(() => this.Close(), System.Windows.Threading.DispatcherPriority.Background);
}

Or flag the event as handled:

private void LeftDoubleClickCommand(object sender, MouseButtonEventArgs e)
{
    e.Handled = true;
    this.Close();
}