Mike
Mike

Reputation: 325

How to find the pixel coordinates of a selected cell in a WPF gridview

I have been trying for a few days to answer this question. I've found snippets of code which come close but have not given me what I need.

I need to be able to identify the x and y coordinates of a specific cell in a WPF datagrid. the cell will be the selected cell. I also need to be able to determine the exact size of that cell.

this is so that I can superimpose an editor control over that cell when the user edits it so I can accept user input.

the reason it has to be done this way is I need different editors by row. there are several columns in the datagrid. one column in particular asks the user to provide a value. depending on the contents of another column the type of input the user needs to provide in the value column changes. a text input or a number input requires a text box. some rows are boolean and the user needs to select from a check box. some rows have predefined values and the user needs a combo box. there are also file path rows and I want a file open dialog to come up automatically and place the selected filename into the cell. so I can't just use the built in editors in the datagrid because it allows me to specify the format by column, but not also by row. of course I don't know the contents of the rows ahead of time so it needs to be done at runtime.

I have been able to move the editor controls around and make them visible and invisible. I have been able to get the X coordinate of the left side of the selected cell. I've also been able to find the width of the selected cell.

the Y coordinate of the cell and the height of the cell I have attempted in several different ways but none have worked.

I already have the logic flow figured out for how to do this. I did a sample run in a window forms application. 100 lines of code and about 30 minutes and it was working perfectly. I've been trying to figure out how to do the same thing in WPF for days. any help would be appreciated.

Upvotes: 0

Views: 2346

Answers (1)

coldandtired
coldandtired

Reputation: 1043

Here's a not very elegant solution:

private void grid_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Point point;
        Point point2;

        TextBlock tb = (TextBlock)e.OriginalSource;
        DataGridCell dgc = (DataGridCell)tb.Parent;
        point = e.GetPosition(dgc);
        point2 = e.GetPosition(this);
        double cell_width = dgc.ActualWidth;
        double absolute_x = point2.X - point.X;
    }

Only the X is there, but it's the same for the Y. The main problem is that a switch will be needed to determine the source (TextBlock, Border, etc.) and that this works when the cell is clicked the second time (although that might be changeable with properties).

Upvotes: 1

Related Questions