1
votes

I have a simple user control to display a hyperlink in a textblock:

LinkTextBlock.xaml:

<TextBlock >
    <Hyperlink NavigateUri="{Binding Url, ElementName=root}" >
        <TextBlock Text="{Binding Text, ElementName=root}" />
    </Hyperlink>   
</TextBlock>

LinkTextBlock.xaml.cs:

public static readonly DependencyProperty UrlProperty = DependencyProperty.Register("Url", typeof (string), typeof (LinkTextBlock));
public string Url
{
    get { return (string) GetValue(UrlProperty); }
    set { SetValue(UrlProperty, value); }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string), typeof (LinkTextBlock));
public string Text
{
    get { return (string) GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}


Then, in a DataTemplate for a ListBox I have:

<Controls:LinkTextBlock Text="{Binding Email}" Url="{Binding Email}" />


When I run the application, it seems to work perfectly. The control shows the hyperlinks correctly and there are no apparent problems. However, when I look at the Output window I get exceptions, one for each ListBox item:

System.Windows.Data Error: 22 : Cannot convert '' from type '' to type 'System.Uri' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: UriTypeConverter cannot convert from (null). at System.ComponentModel.TypeConverter.GetConvertFromException(Object value) at System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at System.UriTypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)'

Why is this happening? I know the binding error is a result of the binding to NavigateURI. Do you have any suggestions for me? What can I do about it? I really appreciate your inputs.

Thanks

2
What kind of object is "Email" coming from. What is its type?PeterAllenWebb
Peter, Email is just a string property of the object bound to the current DataContext.Gus Cavalcanti

2 Answers

5
votes

I figured it out. The problem is when performing an implicit conversion from string to Uri, since NavigateUri is of type Uri. I needed to create a converter to convert string to Uri, change my property from String to Uri, and it all worked fine without exceptions.

-1
votes

Shouldn't this

<TextBlock >
    <Hyperlink NavigateUri="{Binding Url, ElementName=root}" >
        <TextBlock Text="{Binding Text, ElementName=root}" />
    </Hyperlink>   
</TextBlock>

be this?

<TextBlock  Text="{Binding Text, ElementName=root}">
    <Hyperlink NavigateUri="{Binding Url, ElementName=root}" />
</TextBlock>