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

In a Xamarin.Forms project, I am trying to resolve underlined shortcuts. So I have my own renderer and I am trying to do something simple:

Control.TextDecorations = TextDecorations.Underline;

      

It compiles just fine, but when the app starts, I get an InvalidCastException on this line that says:

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

Here is a screenshot of the exception:

enter image description here

Also, when inspecting the control, I noticed that there are a ton of InvalidCastExceptions for other properties of the TextBlock control: here's a small example:

enter image description here

Why is he trying to use the type ITextBlock5

? Is this a UWP bug? Is there a workaround to highlight the work?

+1


source to share


2 answers


According to Microsoft documentation, the TextDecorations property was not introduced until version 15063. You are probably getting this exception on an earlier version of Windows.

As a workaround, you can create an object Underline()

and add the object Run()

to the Inlines Inline collection, for example:

// 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 Inline collection
Control.Inlines.Add(underlinedText);

      



Inside the custom render override method, OnElementChanged()

it will look something like this:

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

      

0


source


The property is TextDecorations

documented on MSDN for support in version 15063 and later.



You can use the class ApiInformation

to check at runtime if a property is available or not.

0


source







All Articles