在运行时在 Xamarin Forms 中绑定标签的 FormattedString 的跨度
Bind a span of a FormattedString of a Label in Xamarin Forms at runtime
在 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]");
在 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]");