Maui StringFormat 在标签中,可以内联更改 FontAttribute 吗?

Maui StringFormat in label, possible to change FontAttribute inline?

提问人:Bob 提问时间:9/26/2023 更新时间:9/26/2023 访问量:80

问:

真的很基本的问题,但我找不到答案:

是否可以更改已格式化标签中字符串的字体属性?

具体来说,我有这个:Label

<Label Style="{StaticResource MediumLabel}"
       Text="{Binding TimeStart, StringFormat='Time start: {0:F0}'}" />

它最终看起来像这样:

时间开始:13:32:46

当我希望它看起来像这样时:

时间开始:13:32:46

或者这个:

时间开始:13:32:46

这可能吗?

C# 数据绑定 Maui 字符串格式

评论

1赞 Stephen Quan 9/26/2023
learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/......显示需要使用 Label.FormattedText,其中 FormattedString 包含多个 Span 元素。您不能使用 StringFormat 执行此操作。
0赞 Bob 9/26/2023
是的,我读了那个,也没有看到答案。我想你想不出解决方法吗?(我可以删除字符串格式,只需将两个元素并排放置,文本和绑定标签。这可能是最好的方法。Time start:13:32:46 (or whatever the Time is)
0赞 Stephen Quan 9/26/2023
简单地说,是的,两个标签。如果你想变得超级花哨,你可以有一个伪HTML解析器或MarkDown解析器,它将输入文本分解为文本元素的List/Collection,你可以用它来用BindableLayout填充FlexLayout。

答:

1赞 Stephen Quan 9/26/2023 #1

如果你很好奇,我有一个工作版本的分线器。假设您的 ViewModel 设置为 ,以下是使用正则表达式将其分解为格式化文本的方法:string Message"Time Start: *13:32:46*"

public class FormattedText
{
    public string Text { get; set; }
    public Color TextColor { get; set; } = Colors.Black;
    public FontAttributes FontAttributes { get; set; } = FontAttributes.None;
}

然后,您可以定义一个 getter 以使用以下命令:IList<FormattedText> FormattedMessage

public IList<FormattedText> GetFormattedMessage(string message)
{
    List<FormattedText> Result = new List<FormattedText>();
    string pat = @"\*([^\*]*)\*|([^*]+)";
    Match match = Regex.Match(message, pat);
    while (match.Success)
    {
        if (match.Groups[1].Success)
        {
            Result.Add(new FormattedText() { Text = match.Groups[1].Value, FontAttributes = FontAttributes.Italic});
        }
        if (match.Groups[2].Success)
        {
            Result.Add(new FormattedText() { Text = match.Groups[2].Value, FontAttributes = FontAttributes.None });
        }
        match = match.NextMatch();
    }
    return Result;
}

然后,可以在 XAML 中呈现 in:FormattedMessageFlexLayout

<FlexLayout HorizontalOptions="Fill"
            BindableLayout.ItemsSource="{Binding FormattedMessage}">
    <BindableLayout.ItemTemplate>
        <DataTemplate>
            <Label Text="{Binding Text}"
                   TextColor="{Binding TextColor}"
                   FontAttributes="{Binding FontAttributes}"
                   Padding="5"/>
        </DataTemplate>
    </BindableLayout.ItemTemplate>
</FlexLayout>