Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Monday, 28 May 2018

How to concatenate text with binding value in label control in Xamarin Forms - Solved


This blog is all about – to concatenate text with binding value in label control in Xamarin Forms.

Actually, you can bind value in two ways: -

I. Binding concatenated text and value in XAML or View.
In this case, if you want to directly bind your concatenate value with text in XAML page itself. This is the easiest way to do so because Label in Xamarin forms supports StringFormat property. The only thing is to create a property and bind it to the View.

For Example:

In Code behind (XAML.CS):

public string Name { get; }

public BindingConcatTextValue()
{
    InitializeComponent();
    Name = "Imagination Hunt";
    BindingContext = this;
}

Then in XAML or View:

<Label Text="{Binding Name, StringFormat='Customer Name : {0}'}" />

Here, StringFormat does the task to add Text+Value in View and BindingContext bind the value from CodeBehind to View.

Output: Customer Name : Imagination Hunt



II. Binding concatenated text and value in XAML.CS ÓR .CS page
In this case, you should create a new property which does the format you want and binds it to the View. And make sure the property is public.

For Example:

In View Model (.CS):

public class BindingConcatTextValueViewModel
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public string CustName { get; set; }

    public BindingConcatTextValueViewModel()
    {
        CustName = "Imagination Hunt";
        Name = string.Format("Customer Name: {0}", CustName);
    }
}

Then in Code-Behind (XAML.CS)

public string Name { get; }
public string CustName { get; set; }

public BindingConcatTextValue2()
{
     InitializeComponent();

     //When you want your label value bind from CodeBehind
     CustName = "Imagination Hunt";
     Name = string.Format("Customer Name: {0}", CustName);
     BindingContext = this;

     //Or when you want your label value bind from ViewModel
     BindingContext = new BindingConcatTextValueViewModel();
}


Then in XAML:

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

Output: Customer Name: Imagination Hunt


Hope you find the article helpful and interesting. For any query, comment us below.

Previous - What is Xamarin?
 

Related Questions: -


Ques - How you connect these “Name” property to your View or XAML page?
Ans. – BindingContext.

Click imagination hunt to read latest blogs.



Keep learning and sharing...

No comments:

Post a comment

Featured post

Think that makes you rich and richer

 Napolean said: “You can think and grow rich, but if you can be brought up like most people with work and you won't starve, this wil...