首页 > 解决方案 > xamarin 表单中标签的数据绑定部分

问题描述

我在 Xamarin 表单中使用标签。我必须显示一个基本上是一个句子的文本,但该字符串的一部分包含一个我从 api 调用中获得的数字,并且字符串的其余部分是固定的。

我想使用数据绑定来设置那部分。例子 :

文本可以是:“你肯定能赢 {0} 美元”

{0} 值来自 api 并希望使用数据绑定来绑定它。

需要用于绑定此类字符串的语法。

标签: xamarin.forms

解决方案


您可以使用模型绑定到标签中的数据。就像这样:在 xaml 中:

 <Label Text="{Binding Name,StringFormat='You can win {0} dollars for sure'}" 
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" />

在 ContentPage 中,应该绑定上下文:

 nativeDataTemple = new NativeDataTemple();
 BindingContext = nativeDataTemple;

并且 Molde(您自定义的NativeDataTemple)应该包含绑定属性,如下所示:

private string name = "520";
    public string Name
    {
        set
        {
            if (name != value)
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
        get
        {
            return name;
        }
    }

并在您的模型中,当名称值在后台更改时,将INotifyPropertyChanged添加到模型中,并添加方法

 protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

那么你想在哪里更改数据,只需这样做:

nativeDataTemple.Name = "550";

有问题可以参考这个官方文档


推荐阅读