Wednesday, March 28, 2012

Creating a hyperlink with both text and link, WPF

[WPF, C#] We generally use hyperlink in order to navigate to certain URL but have you ever wonder how you'll display a string with hyperlink in it? E.g. In help menu of your application, you need to show something link "For more information please contact 123-456-7890 or email". In this string, 'email' is a hyperlink, clicking on which open the outlook.

There is no simple or built in control for such thing and even you can't do this by clubbing text & hyperlink together in a grid. Here is a workaround to achieve this in code behind of your XAML file.

Add a hyperlink in xaml and don't specify it's text/content there, instead the content is specified using code behind in constructor of that usercontrol.

// string you need to show on GUI
string contactSupport = "For more information please contact 123-456-7890 or email";
// place holder constant. Content which you want to create hyperlink
const string EMAIL_PLACEHOLDER = "email";
string[] stringSeparators = new string[] {EMAIL_PLACEHOLDER };
// create hyperlink which will be called on clicking 'email'
Hyperlink hyperlink = new Hyperlink(){ 
NavigateUri = new URI("mailto:")
// text to show for hyperlink content. Email here
hyperLink.RequestNavigate += Hyperlink_RequestNavigate;

// hyperlink created now you need to break the text string into two string one will be displayed as simple text and another will be hyperlink.
string beforeText = contactSupport.Split(stringSeparators, StringSplitOptions.None)[0];
string afterText = contactSupport.Split(stringSeparators, StringSplitOptions.None)[1];
//Now you've both text and hyperlink add them in the hyperlink which you've created in xaml
// 1. First part of text is added to that hyperlink. It will be displayed as simple text
this.supportHyperlink.Inlines.Add(new Run(beforeText));
// 2. Add hyperlink
// 3. Add any other text, if any you want to add after the hyperlink.
this.supportHyperlink.Inlines.Add(new Run(afterText));

Now, you're ready to use the hyperlink with both simple text & hyperlink.

No comments:

Post a Comment