0

I have a label with TextType="Html" in my xamarin forms App. I am trying to bind the following html text. Get help with your health related questions <strong style="color:#007ABC;">when you sign up to become an awesome holder.</strong>. The weird issue I am facing is when I put this text directly into Xaml, the text getting rendered properly with the color and everything. But when I try to bind this from backend, ie; from a string property in viewmodel, the text will not get rendered correctly. Please refer the screenshot attached. Is there any internal conversion happening? How to tackle this issue because I have to get this from the API. Any help is appriciated. Screenshot

8
  • I don’t think you need to encode the HTML when binding from the VM Commented Oct 14, 2023 at 17:40
  • @Jason The problem is the same html text is showing like this in the screenshot when binding from VM. But it works just fine when directly hardcoding in the Xaml Commented Oct 14, 2023 at 17:41
  • @Jason and what you meant by encoding? Commented Oct 14, 2023 at 17:42
  • HTML must be encoded to be included in an XML document. When you use binding it isn’t included in the document so it doesn’t need to be encoded Commented Oct 14, 2023 at 17:59
  • encoding is translating a character like < into &lt; Commented Oct 14, 2023 at 18:41

1 Answer 1

1

You may refer to this document Display HTML. And you could see the differences between using XAML and using code behind.

&lt; in XAML convert to < in code behind

&quot; in XAML convert to \" in code behind. (Note: The double quote characters in the HTML have to be escaped using the \ symbol.)

So the origin string works for XAML may equal to this in code behind:

Get help with your health related questions <strong style=\"color:#007ABC;\">when you sign up to become an awesome holder.</strong>";

So the easiest way i think is that you could use a String.Replace method to convert the string.

For example,

CodeBehindString = XAMLString.Replace("&lt;","<").Replace("&gt;",">").Replace("&quot;","\"");

Or you may use Xamarin.Forms Binding Value Converters as Jason said.

Hope it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This worked System.Net.WebUtility.HtmlDecode(htmlstring);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.