提问人:Bob 提问时间:9/26/2023 更新时间:9/26/2023 访问量:80
Maui StringFormat 在标签中,可以内联更改 FontAttribute 吗?
Maui StringFormat in label, possible to change FontAttribute inline?
问:
真的很基本的问题,但我找不到答案:
是否可以更改已格式化标签中字符串的字体属性?
具体来说,我有这个:Label
<Label Style="{StaticResource MediumLabel}"
Text="{Binding TimeStart, StringFormat='Time start: {0:F0}'}" />
它最终看起来像这样:
时间开始:13:32:46
当我希望它看起来像这样时:
时间开始:13:32:46
或者这个:
时间开始:13:32:46
这可能吗?
答:
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:FormattedMessage
FlexLayout
<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>
上一个:设置字符串格式以插入小数点
评论
Time start:
13:32:46 (or whatever the Time is)