user3102153
user3102153

Reputation: 33

Bind a span of a FormattedString of a Label in Xamarin Forms at runtime

In Xamarin Forms i want to create formated label inside a collectionView. The label will be created based on many values from a ItemArray. If i create the label in design using xaml it is working fine:

<Label  VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding ItemArray[0]}"  TextColor="Blue"/>
<Span Text="{Binding ItemArray[1]}"  TextColor="Red"/>
<Span Text="{Binding ItemArray[2]}"  TextColor="Blue"/>
</FormattedString>
</Label.FormattedText>

When i try to create the label at runtime i get for the Text the "{Binding ItemArray[0]}" and not the actual value

StackLayout ST2 = new StackLayout { Orientation = StackOrientation.Horizontal };
Label LB1 = new Label
{
FormattedText =
new FormattedString
{
Spans =
{
new Span { Text = "{Binding ItemArray[0], Mode=OneWay}", ForegroundColor = Color.Blue },
new Span { Text = "{Binding ItemArray[1], Mode=OneWay}", ForegroundColor = Color.Red },
new Span { Text = "{Binding ItemArray[2], Mode=OneWay}", ForegroundColor = Color.Blue }
}
}
};

ST2.Children.Add(LB1);

Upvotes: 0

Views: 1270

Answers (1)

Jason
Jason

Reputation: 89082

use SetBinding

var span = new Span() { ForegroundColor = Color.Blue };
span.SetBinding (Span.TextProperty, "ItemArray[0]");

Upvotes: 1

Related Questions