我有一个简单的用户控件来在文本块中显示超链接:
LinkTextBlock.xaml:
<TextBlock >
<Hyperlink NavigateUri="{Binding Url, ElementName=root}" >
<TextBlock Text="{Binding Text, ElementName=root}" />
</Hyperlink>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
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); }
}
Run Code Online (Sandbox Code Playgroud)
然后,在 ListBox 的 DataTemplate 中,我有:
<Controls:LinkTextBlock Text="{Binding Email}" Url="{Binding Email}" />
Run Code Online (Sandbox Code Playgroud)
当我运行该应用程序时,它似乎运行良好。控件正确显示超链接,没有明显问题。但是,当我查看“输出”窗口时,我得到了异常,每个 ListBox 项都有一个异常:
System.Windows.Data 错误:22:无法使用默认转换将 '' 从类型 '' 转换为类型 'System.Uri' 的“en-US”文化;考虑使用 Binding 的 Converter 属性。NotSupportedException:'System.NotSupportedException: UriTypeConverter 无法从 (null) 转换。在 System.ComponentModel.TypeConverter.GetConvertFromException(Object value) at System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at System.UriTypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfoculture, Object value) at MS.Internal .Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfoculture, Boolean isForward)'
为什么会这样?我知道绑定错误是绑定到 NavigateURI 的结果。你对我有什么建议吗?我该怎么办?我非常感谢您的投入。
谢谢
我想到了。问题在于执行从字符串到 Uri 的隐式转换时,因为 NavigateUri 是 Uri 类型。我需要创建一个转换器来将字符串转换为 Uri,将我的属性从 String 更改为 Uri,并且一切正常,无一例外。