WPF – Cannot convert ‘‘ from type ‘‘ to type ‘System.Uri’

data-bindingwpf

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

Best Answer

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.

Related Topic