Search code examples
xamarinmvvmdata-binding

Bind from backend but not front-end (Xamarin-C#)


I want to bind a model to a view. The problem is that it doesn't bind.

this.BindingContext = Model;
stackLayoutF.Children.Add(new Entry() { Text = Model.EditFirstname, WidthRequest = 100 });
stackLayoutContent.Children.Add(stackLayoutF);

   private string _editFirstname = "United";

        public string EditFirstname
        {
            get { return _editFirstname; }
            set
            {
                SetProperty(ref _editFirstname, value);
            }
        }

It loads normally with the text "United". When I change the text, nothing happened.

I probably forgotten something.

Please let me know if you can help me with this problemn.


Solution

  • You didn't specify any bindings anywhere. You will need to write something like:

    var entry = new Entry() { WidthRequest = 100 };
    entry.SetBinding(Entry.TextProperty, nameof(ViewModel.EditFirstName));
    
    stackLayoutF.Children.Add(entry);
    

    Refer to the official docs here, there are multiple examples of this: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/basic-bindings