Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf: How to add a Hyperlink at runtime?

I need to add several hyperlinks to the program's form dynamically at runtime (and handle user clicks on them).

How to do this?

I tried something like: var hlink = new Hyperlink(); myStackPanel.Children.Add(hlink);

but hyperlink is not a UIElement...

Thanks!

like image 970
Vitas Avatar asked May 11 '26 20:05

Vitas


1 Answers

It's a little bit kludgy, but you need to do this:

Label linkLabel = new Label();
Run linkText = new Run("Google");
Hyperlink link = new Hyperlink(linkText);

link.NavigateUri = new Uri("http://www.google.com");

link.RequestNavigate += new RequestNavigateEventHandler(delegate(object sender, RequestNavigateEventArgs e) {
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
    e.Handled = true; 
});

linkLabel.Content = link;

myStackPanel.Children.Add(linkLabel);

This will make a new label with the text "Google", the Uri "http://www.google.com", and when clicked it will open the Uri in the user's default browser.

like image 74
Nathan Wheeler Avatar answered May 16 '26 13:05

Nathan Wheeler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!