c#带字符串和数据的多重绑定标签

时间:2018-04-30 04:07:52

标签: c# xamarin

快速提问:

如何用固定字符串本身绑定标签? 与“ID:xxxxx”类似,“ID:”是固定字符串,xxxx是数据 我能做到的唯一方法是在UI中创建两个标签。

无论如何都可以使用一个标签吗?

4 个答案:

答案 0 :(得分:1)

一种方法是创建一个新属性来输出您的自定义格式,例如:

public string MyCustomFormatProperty{
    get {
        return string.Format("ID:{0}",  this.XXX);
    }
}

<Label Text = "{Binding MyCustomFormatProperty}" />

另一种方法是使用转换器: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/converters

答案 1 :(得分:1)

你可以直接在Xaml中这样做:

<Label Text="{Binding Id, StringFormat='ID:{0}'}}"/>

视图模型中不需要转换器或其他属性;)

答案 2 :(得分:0)

您可以使用固定标签字符串

连接字符串

例如:Lable1.Text = Lable1.Text +“xxxxxxx”;

我认为这是你的问题所需要的。

答案 3 :(得分:0)

对于过去的项目,我已经创建了自己的自定义标签类,它具有多个可绑定的值属性,只能将这些值连接在一起。

public class MultiLabel : Label
{
    public static readonly BindableProperty Value1Property = BindableProperty.Create(nameof(Value1), typeof(string), typeof(MultiLabel), string.Empty, propertyChanged: OnValueChanged);
    public static readonly BindableProperty Value2Property = BindableProperty.Create(nameof(Value2), typeof(string), typeof(MultiLabel), string.Empty, propertyChanged: OnValueChanged);
    public static readonly BindableProperty Value3Property = BindableProperty.Create(nameof(Value3), typeof(string), typeof(MultiLabel), string.Empty, propertyChanged: OnValueChanged);
    public static readonly BindableProperty Value4Property = BindableProperty.Create(nameof(Value4), typeof(string), typeof(MultiLabel), string.Empty, propertyChanged: OnValueChanged);
    public static readonly BindableProperty Value5Property = BindableProperty.Create(nameof(Value5), typeof(string), typeof(MultiLabel), string.Empty, propertyChanged: OnValueChanged);

    public string Value1
    {
        get { return (string)GetValue(Value1Property); }
        set { SetValue(Value1Property, value); }
    }

    public string Value2
    {
        get { return (string)GetValue(Value2Property); }
        set { SetValue(Value2Property, value); }
    }

    public string Value3
    {
        get { return (string)GetValue(Value3Property); }
        set { SetValue(Value3Property, value); }
    }

    public string Value4
    {
        get { return (string)GetValue(Value4Property); }
        set { SetValue(Value4Property, value); }
    }

    public string Value5
    {
        get { return (string)GetValue(Value5Property); }
        set { SetValue(Value5Property, value); }
    }

    static void OnValueChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var label = (MultiLabel)bindable;

        label.Text = label.Value1 + label.Value2 + label.Value3 + label.Value4 + label.Value5;
    }
}

在xaml

<local:MultiLabel Value1="ID:" Value2="{Binding Id}" />

我们这样做的主要原因是减少标签数量以减少内存占用量,并且所需的值数量总是可以更改它只是因此我们最终需要的最大值是5。