How to get a Grid to raise MouseDown events when no UIElemets in cells clicked?

◇◆丶佛笑我妖孽 提交于 2019-12-25 01:54:22

问题


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?


回答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">


来源:https://stackoverflow.com/questions/20511890/how-to-get-a-grid-to-raise-mousedown-events-when-no-uielemets-in-cells-clicked

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!