【问题标题】:Concatenate string from a variable in XAML Bindings of Xamarin.Forms连接来自 Xamarin.Forms 的 XAML 绑定中的变量的字符串
【发布时间】:2020-05-07 08:21:42
【问题描述】:

在 Xamarin.Forms 项目中,我需要将本地化字符串值与字符串属性的绑定连接起来,

我想实现类似的目标,

<Label Text="{Binding Name}", 
       StringFormat='Created By {0}' />

Created By字符串应该来自,

LocalizedStrings.CreatedBy

我怎样才能做到这一点?

【问题讨论】:

  • 这可以通过使用LabelFormattedText 属性来实现。你试过了吗?

标签: xaml xamarin xamarin.forms


【解决方案1】:

这可以通过使用LabelForamttedText 属性来实现。 MS Docs link

<Label>
    <Label.FormattedText>
        <FormattedString>
            <Span Text="{x:Static Resources:LocalizedStrings.CreatedBy}" />
            <Span Text="{Binding Name, StringFormat=' {0}'}"/>
        </FormattedString>
    </Label.FormattedText>
</Label>

ResourcesLocalizedStrings

的导入

【讨论】:

  • Created By 文本应根据问题来自本地化字符串变量
  • &lt;Span Text="Created By "/&gt; 应该是&lt;Span Text="{x:Static LocalizedStrings.CreatedBy}" /&gt;
【解决方案2】:

在xaml中,添加一个名称来引用标签,

<Label x:Name="myLabel" />

在代码隐藏中,

myLabel.SetBinding(
    Label.TextProperty,
    new Binding(nameof(MyModal.Name), stringFormat: $"{LocalizedStrings.CreatedBy} {{0}}"));

这样我们可以用变量值格式化绑定字符串属性。

替代方法:

您也可以使用 LabelFormattedText 属性,如下所示,但这不是优化的方法

LocalizedStrings 导入到 xmlns:Resources,然后,

<Label>
    <Label.FormattedText>
        <FormattedString>
            <Span Text="{x:Static Resources:LocalizedStrings.CreatedBy}" />
            <Span Text="{Binding Name, StringFormat=' {0}'}"/>
        </FormattedString>
    </Label.FormattedText>
</Label>

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多