Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

c# - Get Grid Cell by mouse click

I have a WPF Grid which is divided into 3 rows and 3 columns, i wasn't able to find a way of getting the row and column number of mouse click on the net, ohh and if it is possible it will be better for my program that this part will be in code and not XAML, this is my simple grid:

  <Grid Name="GridCtrl" ShowGridLines="True">
     <Grid.RowDefinitions>
        <RowDefinition Height="3*" />
        <RowDefinition Height="3*" />
        <RowDefinition Height="3*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="3*" />
        <ColumnDefinition Width="3*" />
        <ColumnDefinition Width="3*" />
   </Grid.ColumnDefinitions>
  </Grid>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Faced with the same problem I came up with this solution:

XAML:

<Grid Name="myGrid" Background="Transparent" PreviewMouseLeftButtonDown="OnPreviewMouseLeftButtonDown">

NOTE: The Grid has to be given a background to raise the mouse down event, see: How to get a Grid to raise MouseDown events when no UIElemets in cells clicked?

Code-behind:

private void OnPreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    if(e.ClickCount == 2) // for double-click, remove this condition if only want single click
    {
        var point = Mouse.GetPosition(myGrid);

        int row = 0;
        int col = 0;
        double accumulatedHeight = 0.0;
        double accumulatedWidth = 0.0;

        // calc row mouse was over
        foreach (var rowDefinition in myGrid.RowDefinitions)
        {
            accumulatedHeight += rowDefinition.ActualHeight;
            if (accumulatedHeight >= point.Y)
                break;
            row++;
        }

        // calc col mouse was over
        foreach (var columnDefinition in myGrid.ColumnDefinitions)
        {
            accumulatedWidth += columnDefinition.ActualWidth;
            if (accumulatedWidth >= point.X)
                break;
            col++;
        }

        // row and col now correspond Grid's RowDefinition and ColumnDefinition mouse was 
        // over when double clicked!
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...