2009-05-05 205 views
1

我有一个简单的用户控件显示一个文本块中的超链接:WPF - 无法从类型 '<null>' 转换'<null>为键入 '的System.Uri'

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); } 
} 


然后,在一个ListBox一个DataTemplate我:

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


当我运行应用程序,它似乎很好地工作。该控件正确显示超链接并且没有明显问题。然而,当我看到在输出窗口,我得到的例外,每一个列表框项:

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)'

这究竟是为什么?我知道绑定错误是绑定到NavigateURI的结果。 对我有什么建议吗?我能做些什么呢?我非常感谢你的投入。

感谢

+0

什么样的对象是来自“电子邮件”。它的类型是什么? – PeterAllenWebb 2009-05-05 18:39:20

+0

Peter,Email只是绑定到当前DataContext的对象的字符串属性。 – 2009-05-05 18:46:21

回答

3

我想通了。问题是执行从字符串到Uri的隐式转换时,因为NavigateUri的类型是Uri。 我需要创建一个转换器将字符串转换为Uri,将我的属性从字符串更改为Uri,并且一切正常,没有例外。

-1

不应该在该

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

是这样?

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

不是。超链接没有可视化表示。所以如果你按照你的建议去做,你最终只需要一个没有任何东西点击的TextBlock。 – 2009-05-05 18:31:42

相关问题