1

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?

Junaid Pathan
  • 3,850
  • 1
  • 25
  • 47

1 Answers1

3

It is important you learn about MVVM pattern and how to perform the data binding. You can see this link: https://learn.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.

Junaid Pathan
  • 3,850
  • 1
  • 25
  • 47
Marcel Callo
  • 411
  • 2
  • 8