Xamarin.Forms UWP - 尝试为 TextBlock 设置 TextDecorations 时出现 InvalidCastException

Xamarin.Forms UWP - InvalidCastException when trying to set TextDecorations for TextBlock

在一个 Xamarin.Forms 项目中,我尝试允许使用带下划线的标签。所以我有一个自定义渲染器,我正在尝试做一些简单的事情:

Control.TextDecorations = TextDecorations.Underline;

它编译得很好,但是当应用程序启动时,我在该行上收到一个 InvalidCastException,上面写着:

System.InvalidCastException: 'Unable to cast object of type 'Windows.UI.Xaml.Controls.TextBlock' to type 'Windows.UI.Xaml.Controls.ITextBlock5'.'

这是异常的屏幕截图:

此外,在检查控件时,我注意到 TextBlock 控件的其他属性也有大量 InvalidCastException 异常 - 这是一个小示例:

为什么要转换为 ITextBlock5 类型?这是 UWP 错误吗?是否有解决方法让下划线起作用?

根据 Microsoft documentation,直到版本 15063 才引入 TextDecorations 属性。您可能会遇到该异常,因为您使用的是 Windows 的早期版本.

作为解决方法,您可以创建一个 Underline() 对象并将一个 Run() 对象添加到 Underline 对象的 Inlines 集合中,如下所示:

// first clear control content
Control.Inlines.Clear();

// next create new Underline object and
// add a new Run to its Inline collection
var underlinedText = new Underline();
underlinedText.Inlines.Add(new Run { Text = "text of xamarin element here" });

// finally add the new Underline object
// to the Control's Inline collection
Control.Inlines.Add(underlinedText);

在自定义渲染器的 OnElementChanged() 覆盖方法中,它看起来像这样:

protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
    base.OnElementChanged(e);
    var view = e.NewElement as LabelExt; // LabelExt => name of PCL custom Label class
    var elementExists = (view != null && Control != null);
    if (!elementExists)
    {
        return;
    }

    // add underline to label
    Control.Inlines.Clear();
    var underlinedText = new Underline();
    underlinedText.Inlines.Add(new Run { Text = view.Text });
    Control.Inlines.Add(underlinedText);
}

TextDecorations 属性 documented on MSDN 将在版本 15063 及更高版本上受支持。

您可以使用 ApiInformation class 在运行时检查 属性 是否可用。