Xamarin.Forms UWP - 尝试为TextBlock

时间:2017-12-07 14:42:49

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

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

Control.TextDecorations = TextDecorations.Underline;

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

  

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

以下是例外情况的屏幕截图:

enter image description here

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

enter image description here

为什么要尝试转换为ITextBlock5类型?这是一个UWP错误吗?是否有一种解决方法可以使下划线工作?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

版本15063及更高版本支持TextDecorations属性为documented on MSDN

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