Home > OS >  How to bind individual html lines to multiple labels in xamarin.forms with c#
How to bind individual html lines to multiple labels in xamarin.forms with c#

Time:12-05

I've just started using binding so this may simple but I haven't found any suitable answers online. I have the labels

<Label x:DataType="myNameSpace:MyClass" Text = "{Binding label}"/>
<Label x:DataType="myNameSpace:MyClass" Text = "{Binding label2}"/>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I need to bind different strings of html from json elements stored in a dynamic dynamicObject; to different labels. So I can't just assign the entire view to a label as Label Class Doc suggests. The C# is

        Label label = new Label();
        label.Text = dynamicObject.mainText;
        label.TextType = TextType.Html;

However, I need to use xaml and it always says that label is not found in the data context MyClass. Even using public String label{get{return "Text";}} does not display anything. What is the most efficient way to do access different strings from the object and display them in different labels?

CodePudding user response:

{Binding label} requires that the BindingContext contain a "public property" named label.

Do you SET BindingContext anywhere? In view constructor, do

BindingContext=new MyClass();.

... modify as needed, to initialize MyClass with whatever data it should have


Then MyClass.cs must look something like this:

public class MyClass
{
    // These must be PUBLIC PROPERTIES.
    public string label { get; set; }
    public string label2 { get; set; }
}

Usage looks like this:

<Label Text = "{Binding label}"/>
<Label Text = "{Binding label2}"/>

Note that, as Jason says, there are no x:DataType attributes. Those are for a different situation.


A common mistake is to not have PROPERTIES.

// This won't work. This is a FIELD, not a property.
public string label;

If you still can't run because of errors that refer to DataContext or DataType, then:

  • REMOVE ALL x:DataType statements in the xaml file. There is probably one in the first few lines of the XAML. <-- ONLY REMOVE IF this is preventing the app from building or running successfully. If it isn't causing any fatal problem, leave it there.

  • IGNORE (disregard) any DataType/DataContext warning from Intellisense - just run it, and see if it works.

If you get that to work, then it is possible to start adding x:DataType statements back in, to eliminate the intellisense warnings. But they don't belong on the individual labels. I consider this an "advanced" topic, and won't say more about it here.

  • Related