wpf: How to add a Hyperlink at runtime?

时光毁灭记忆、已成空白 提交于 2019-12-10 19:49:39

问题


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!


回答1:


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.




回答2:


Hyperlink is not a UI Element but you can add it as content into a Label.

In Xaml it will look like this:

<Label>
<Hyperlink Click="btnRemoveAll_Click">Remove all</Hyperlink>
</Label>

You can use it for many things just as you would use the click-event of a button.



来源:https://stackoverflow.com/questions/3770197/wpf-how-to-add-a-hyperlink-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!