简体   繁体   中英

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

use SetBinding

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM