WPF 4: Change Hyperlink Text and URL using DataBinding

Let us assume we want to create a WPF UI with a ListBox containing list of web sites. This ListBox must contain Hyperlinks and it should be possible to change the Text and URL of these hyperlinks dynamically. Thankfully in WPF, we have the Hyperlink control element which can be clicked and the user navigated to a URL. But what if the end-user wants to reuse the same Hyperlink to navigate to different web sites? Here DataBinding helps to dynamically change the hyperlink element with its text and the navigate URL. The code shown below explains the same mechanism.

Step 1: Open VS2010 and create a WPF application, name it as ‘WPF4_Hyperlink_DataBinding’. In this application, add following classes. These class will be used for information about web sites to be visited:

WPF Observable Collection

Step 2: In this task, we will do the following:
  1. Create an instance of the above Information class in the MainWindow.xaml using Window Resources.
  2. Define the DataTemplate which will contain Grid with two columns, these columns will contain TextBlocks bound with the HyperText and NavigateUri property of the Information class.
  3. The xaml contains ListBox for displaying the data from the information collection class.
  4. The Hyperlink element is contained by the TextBlock. This TextBlock is bound with the SelectedItem property of the ListBox. Once the user selects the Item from the ListBox, using Bindable Run feature of WPF, the HyperLinkText property from the class is bound with Hyperlink element and the NavigateUri property of the Hyperlink element is bound with the NavigateUri property from the source class.
  5. The WebBrowser element will display the web site when the user clicks on the HyperLink element.
The Xaml is as shown below:


Task 3: Run the Application the result will be as below:

WPF change Hyperlink Text

Click on the Hyperlink and the following result will be displayed:


Conclusion: With the Bindable Run property, data binding with the Hyperlink element can be possible in WPF.

Download the source code

Will you give this article a +1 ? Thanks in advance

About The Author

Mahesh is having 10 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

No comments: