2
votes

I need to provide right-click popup context menu support for a cell in a datagrid. As some of you might know with Silverlight 4 DataGrid if you right-click the item, then your selection isn't updated with whatever you right-clicked on.

The related StackOverflow question ( Silverlight Datagrid select on right click ) address most of this issue in that it selects the correct row when using right click.

My question is how to I get the correct column selected?

Thanks, Jaans


Update: I've discovered a static method on the DataGridColumn (and DataGridRow) classes that have helped my create a solution.

1
I have a potential answer... waiting for required 7/8 hours to pass before I may answer my own question.Jaans

1 Answers

2
votes

Not sure this is the best solution, but it seems to work so far.

Here's a generic helper method:

private T GetParentFromVisualTree<T>( DependencyObject dependencyObject ) where T : DependencyObject
{
    // Iteratively traverse the visual tree
    while ( dependencyObject != null && !( dependencyObject is T ) )
        dependencyObject = VisualTreeHelper.GetParent( dependencyObject );

    if ( dependencyObject == null )
        return null;

    return dependencyObject as T;
}

I then use it in the Row_MouseRightButonDown event as per the other StackOverflow question referenced above:

private void DataGrid_LoadingRow( object sender, DataGridRowEventArgs e )
{
    e.Row.MouseRightButtonDown += Row_MouseRightButtonDown;
}

private void DataGrid_UnloadingRow( object sender, DataGridRowEventArgs e )
{
    e.Row.MouseRightButtonDown -= Row_MouseRightButtonDown;
}

private void Row_MouseRightButtonDown( object sender, MouseButtonEventArgs e )
{
    var dataGridRow = sender as DataGridRow;
    if (dataGridRow == null)
        return;

    // Select the row
    DataGrid.SelectedItem = dataGridRow.DataContext;

    // Select the column
    var dataGridCell = GetParentFromVisualTree<DataGridCell>( e.OriginalSource as DependencyObject );
    if ( dataGridCell != null )
    {
        var dataGridColumn = DataGridColumn.GetColumnContainingElement( dataGridCell );
        DataGrid.CurrentColumn = dataGridColumn;
    }
}