ThomasAndersson
ThomasAndersson

Reputation: 1904

Hyperlink in WPF DataGrid stopping row from being selected

I have a DataGrid with a template column with a Hyperlink as template

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <TextBlock>
            <Hyperlink Command="{Binding Path=OpenCommand}">
                <TextBlock Text="{Binding Path=Description}" />
            </Hyperlink>
        </TextBlock>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

The DataGrid also have a contextmenu with commands for the selected row. When the user right clicks a row in any other columns than the hyperlink column, the row gets selected and context menu is displayed. The problem I have is when the user right clicks on the hyperlink, in order to see commands for that row, the row does not automatically gets selected.

Question: How can I make the Hyperlink ignore the right mouse click, and let the datagrid take care of the event and select the row just like in the other columns?

Upvotes: 0

Views: 1194

Answers (1)

Peter Hansen
Peter Hansen

Reputation: 8907

I'm not sure what causes this behavior, but it sure is annoying.

I don't know if you can do something to the Hyperlink or the DataGrid to somehow make it work, but I think not.

Luckily there is a workaround that works pretty good.

You can subscribe to the MouseRightButtonDown event on the DataGridRows, and set the IsSelected property to true when the event is raised. That way the correct row will be selected even if you click on the Hyperlink.

Add the eventhandler in XAML like this:

<DataGrid.Resources>
    <Style TargetType="DataGridRow">
        <EventSetter Event="MouseRightButtonDown" Handler="DataGridRow_MouseRightButtonDown" />
    </Style>
</DataGrid.Resources>

..and in the code-behind set the selection:

protected void DataGridRow_MouseRightButtonDown(object sender, EventArgs e)
{
    var row = (DataGridRow)sender;
    row.IsSelected = true;
}

Upvotes: 2

Related Questions