简体   繁体   中英

How to bind simple string object to a Label Text in Xamarin Forms?

I am new in Xamarin development, so please bear if the question seems too simple. I am having a simple single string object in my C# code (Code behind). I want to bind it to a Label in XAML so that whenever the string changes, it reflects in XAML Page.

Here is my C# code

public string Name { get; set; }

public HomePage()
{
    InitializeComponent();
    BindingContext = this;
    Name = "John";
}

Here is my XAML code

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

How can I do it. Am I doing anything wrong?

It is important you learn about MVVM pattern and how to perform the data binding. You can see this link: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm .

Basically, you can do this:

Create a ViewModel for your HomePage.

public class HomePageViewModel : INotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
            OnPropertyChanged(nameof(Name));
        }
    }
    public HomePageViewModel()
    {
        // some initialization code here ...
        Name = "John";
    }

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

}

Attach now your ViewModel to the HomePage View

public HomePageView()
{
    InitializeComponent();
    BindingContext = new HomePageViewModel();
}

Then in your XAML, you can have your binding like this:

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

Then whenever the Name changes in the ViewModel, it will be reflected in the XAML view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM