axa
axa

Reputation: 520

How to bind a view control's FormattedText property to its data model

Im trying to format my text and keep all style/format code in the view rather than in the data model.

So using a DataTemplate I create simply a Label. I want to then format the Label's Text for example with color and bold and prefix it with a constant. But im unable to figure out what needs to go in the Span Text property.

internal class BleDeviceDiagnosticItemDataTemplate : DataTemplate
{
    internal BleDeviceDiagnosticItemDataTemplate()
    {
        LoadTemplate = static () =>
        {
            Label idLabel = new() { Text = "default text" };
            idLabel.SetBinding(Label.TextProperty, "Id");

            FormattedString formattedId = new();
            formattedId.Spans.Add(new() { Text = ??? , TextColor = Colors.Red, FontAttributes = FontAttributes.Bold });
            idLabel.FormattedText = formattedId;
        }
    }
}

So while setting the Span Text property with a constant works, for example "Some Text":

Text = "Some Text"

Setting it to the Label.Text doesn't:

Text = Label.Text;

And leaving it out leaves it with no text.

I also tried binding the Label.FormattedText property and setting it in the code behind but that didnt work at all.

idLabel.SetBinding(Label.FormattedTextProperty, "IdFormattedString");

I need advise on how to bind this Text Property to data

Upvotes: 0

Views: 95

Answers (1)

axa
axa

Reputation: 520

Welp i feel kinda cheesy answering my own question here as the answer turns out pretty obvious.... but it seems you just need to bind the data to the Span Text property, not the FormattedString, not to the Label.

FormattedString formattedId = new();
Span idText = new(){ TextColor = Colors.Orange };
idText.SetBinding(Span.TextProperty, nameof(BleDeviceItem.Id));
formattedId.Spans.Add(idText);
idLabel.FormattedText = formattedId;

Upvotes: 0

Related Questions