【问题标题】:Xamarin.Forms UWP - InvalidCastException when trying to set TextDecorations for TextBlockXamarin.Forms UWP - 尝试为 TextBlock 设置 TextDecorations 时出现 InvalidCastException
【发布时间】:2018-05-21 16:57:42
【问题描述】:

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

Control.TextDecorations = TextDecorations.Underline;

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

System.InvalidCastException: '无法将'Windows.UI.Xaml.Controls.TextBlock'类型的对象转换为'Windows.UI.Xaml.Controls.ITextBlock5'类型。'

这是异常的截图:

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

为什么它试图转换为 ITextBlock5 类型?这是 UWP 错误吗?有没有让下划线起作用的解决方法?

【问题讨论】:

  • 您运行的是什么版本的 Windows?
  • Windows 10 专业版,版本 1511,操作系统内部版本 10586.1045

标签: xamarin xamarin.forms uwp textblock xamarin.uwp


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2015-08-23
      • 2016-04-29
      相关资源
      最近更新 更多