Convert urls to Hyperlinks with the IvalueConverter

In my TwitterViewer in WPF I found that status can have urls in the body so they can’t be bind directly to a TextBlock. With a Converter I find maybe a good solution : Split the text with a regular expression, build inline elements (simple Run for text and Hyperlink for urls) and put them in the Inlines property of the TextBlock :

<Label Margin=“8,0,8,0” x:Name=“status” Grid.Column=“1” >
<Binding Path=“Text” Converter="{StaticResource urlConverter}"/>

And the code of the Converter implementation :

String[] LinksText = Regex.Split((String)value, @"(\bhttp://[^ ]+\b)"); TextBlock txtBlock = new TextBlock(); txtBlock.TextWrapping = System.Windows.TextWrapping.Wrap; foreach (String textSplit in LinksText) { if (textSplit.Length > 0) { if (textSplit.Substring(0, 1).Equals(“h”)) { Hyperlink textFormate = new Hyperlink(new Run(textSplit)); textFormate.NavigateUri = new Uri(textSplit); txtBlock.Inlines.Add(textFormate); } else { txtBlock.Inlines.Add(new Run(textSplit)); } } } return txtBlock;

billet publié dans les rubriques coding le