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:
Step 2: In this task, we will do the following:
- Create an instance of the above Information class in the MainWindow.xaml using Window Resources.
- 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.
- The xaml contains ListBox for displaying the data from the information collection class.
- 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.
- The WebBrowser element will display the web site when the user clicks on the HyperLink element.
Task 3: Run the Application the result will be as below:
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