在运行时绑定Xamarin Forms中标签的FormattedString的跨度



在Xamarin Forms中,我想在collectionView中创建格式化标签。标签将基于ItemArray中的许多值创建。如果我在设计中使用xaml创建标签,它可以正常工作:

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

当我试图在运行时创建标签时;{Binding ItemArray[0]}";而不是实际值

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

使用SetBinding

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

最新更新