0

I observe Mouse.MouseDown and PreviewMouseLeftButtonDown are only raised when the mouse is clicked in a cell that contains a UIElement, e.g.:

XAML

<Window xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="WpfApplication5.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="300" Height="300">
    <Grid Mouse.MouseDown="Grid_MouseDown" PreviewMouseLeftButtonDown="Grid_PreviewMouseLeftButtonDown">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="100"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="100"/>
            <RowDefinition Height="100"/>
        </Grid.RowDefinitions>
        <Rectangle Grid.Column="2" Grid.RowSpan="2" Fill="Red"/>
    </Grid>
</Window>

Code-behind

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

    private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Debug.WriteLine("PreviewMouseLeftButtonDown raised!");
    }

    private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Debug.WriteLine("MouseDown raised!");
    }
}

The lines are only written to Debug when the red rectangle is clicked. How can I get the events, or at least one of them, to be raised the grid contains nothing?

markmnl
  • 11,116
  • 8
  • 73
  • 109

1 Answers1

1

I do not know the cause of the issue, but as a workaround giving the Grid a background, even Transparent, seems to make the events be raised!

<Grid Background="Transparent" Mouse.MouseDown="Grid_MouseDown" PreviewMouseLeftButtonDown="Grid_PreviewMouseLeftButtonDown">
markmnl
  • 11,116
  • 8
  • 73
  • 109
  • That's not the issue, that is the default behavior. – Sriram Sakthivel Dec 11 '13 at 06:44
  • @SriramSakthivel there is nothing in documentation about it being the behaviour, why would it be the default? – markmnl Dec 11 '13 at 06:57
  • I don't know where it is documented but this will answer your question http://stackoverflow.com/a/5344709/2530848\ – Sriram Sakthivel Dec 11 '13 at 07:01
  • @SriramSakthivel nope that does not answer my question, I already know Transparent is Brush and no-doubt that has something to do with why the work-around works, but does not explain the issue – markmnl Dec 11 '13 at 07:12
  • I learnt this in pluralsight tutorial by IanGrithfs. I have no clue about where is the documentation sorry:) – Sriram Sakthivel Dec 11 '13 at 07:16
  • @markmnl - Default background will be `x:Null` which is not hit test visible i.e. not allow mouse events. Refer to this [here](http://stackoverflow.com/a/2507252/632337). – Rohit Vats Dec 11 '13 at 09:12