【问题标题】:Data Binding part of a label in xamarin formsxamarin 表单中标签的数据绑定部分
【发布时间】:2018-10-24 01:16:27
【问题描述】:

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

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

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

{0}值来自api,想用数据绑定来绑定。

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

【问题讨论】:

    标签: xamarin.forms


    【解决方案1】:

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

     <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;
            }
        }
    

    在你的模型中,当Name值在后台发生变化时,将INotifyPropertyChanged添加到模型中,以及方法

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

    然后你想改变数据的地方,就这样做:

    nativeDataTemple.Name = "550";
    

    有问题可以参考这个Official document

    【讨论】:

      【解决方案2】:

      在标签中使用跨度

      <Label>
        <Label.FormattedText>
          <FormattedString>
            <Span Text="You can win " />
            <Span Text="{Binding DollarAmount}" />
            <Span Text=" dollars for sure." />
          </FormattedString>
        </Label.FormattedText>
      </Label>
      

      【讨论】:

        猜你喜欢
        • 2016-08-27
        • 2016-06-26
        • 2018-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-15
        • 2019-03-19
        相关资源
        最近更新 更多