You can create a custom control that parses the text value and renders either a textblock or hyperlinkbutton based on the string. Something like this:<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourNamespaceHere">
<Style TargetType="local:LinkLabel">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:LinkLabel">
<StackPanel Margin="2,0,2,0" VerticalAlignment="Center">
<TextBlock x:Name="LabelText" Visibility="Collapsed" />
<HyperlinkButton x:Name="LinkText" Visibility="Collapsed" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
[TemplatePart(Name = "LabelText", Type = typeof(TextBlock)),
TemplatePart(Name = "LinkText", Type = typeof(HyperlinkButton))]
public class LinkLabel : Control
{
private TextBlock _labelText;
private HyperlinkButton _linkText;
private const string Pattern = @"\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]";
public LinkLabel()
{
DefaultStyleKey = typeof(LinkLabel);
}
public string TextValue
{
get { return (string)GetValue(TextValueProperty); }
set { SetValue(TextValueProperty, value); }
}
public static readonly DependencyProperty TextValueProperty =
DependencyProperty.Register("TextValue", typeof(string), typeof(LinkLabel), new PropertyMetadata(string.Empty, TextValuePropertyChanged));
private static void TextValuePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var linkLabel = sender as LinkLabel;
if (linkLabel != null) linkLabel.Refresh();
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_labelText = (TextBlock)GetTemplateChild("LabelText");
_linkText = (HyperlinkButton)GetTemplateChild("LinkText");
Refresh();
}
public void Refresh()
{
if (_labelText == null || _linkText == null)
return;
var regex = new Regex(Pattern);
if (string.IsNullOrWhiteSpace(TextValue) || !regex.IsMatch(TextValue))
{
_labelText.Text = TextValue;
_labelText.Visibility = Visibility.Visible;
_linkText.Visibility = Visibility.Collapsed;
}
else
{
_linkText.Content = TextValue;
_linkText.NavigateUri = new Uri(TextValue, UriKind.RelativeOrAbsolute);
_labelText.Visibility = Visibility.Collapsed;
_linkText.Visibility = Visibility.Visible;
}
}
}