How to handle click event of DataGridHyperlinkColumn programatically through code(in .xaml.cs file).
Asked
Active
Viewed 1.5k times
2 Answers
17
If you just want to navigate the browser to the link, it's a simple as writing a handler like this:
void EventSetter_OnHandler(object sender, RoutedEventArgs e)
{
var destination = ((Hyperlink) e.OriginalSource).NavigateUri;
Process.Start(destination.ToString());
}
If you instead want to take some custom action upon navigation, using information in the associated row, then you will need to access the data context of the hyperlink:
void EventSetter_OnHandler(object sender, RoutedEventArgs e)
{
var rowData = ((Hyperlink) e.OriginalSource).DataContext as User;
navigationService.NavigateToUserRecordForId(rowData.Id);
}
If you want to programatically create a hyperlink column, and bind to it's click event, you can do this:
var style = new Style(typeof(TextBlock));
style.Setters.Add(new EventSetter(Hyperlink.ClickEvent, (RoutedEventHandler)EventSetter_OnHandler));
var column = new DataGridHyperlinkColumn { Header = "User", Binding = new Binding("ViewUserLink"), ElementStyle = style };
dataGrid1.Columns.Add(column);
This stack overflow answer also has good info on the WPF toolkit's Data GridHyperlinkColumn, well worth checking out.

Community
- 1
- 1

Bittercoder
- 11,753
- 10
- 58
- 76
-
In .NET 6, `Process.Start("https://someurl")` results in exception like: `System.ComponentModel.Win32Exception: 'An error occurred trying to start process 'https://google.com/' with working directory 'D:\Projects\(...)\bin\Debug\net6.0-windows'. The system cannot find the file specified.'`. This code works better: https://stackoverflow.com/questions/21835891/process-starturl-fails/61035650#61035650 – Paweł Bulwan Jun 30 '22 at 10:49
12
use this:
<dg:DataGridHyperlinkColumn.ElementStyle>
<Style TargetType="TextBlock">
<EventSetter Event="Hyperlink.Click" Handler="OnHyperlinkClick" />
</Style>
</dg:DataGridHyperlinkColumn.ElementStyle>
</dg:DataGridHyperlinkColumn>

viky
- 17,275
- 13
- 71
- 90