Starting Xamarin with MVVM binding in Code

Create your view model which implements INotifyPropertyChanged:

public class ViewModel : INotifyPropertyChanged
{
private string someValue;
public event PropertyChangedEventHandler PropertyChanged;

public string SomeValue
{
get { return someValue; }
set
{
if (someValue!= value)
{
someValue= value;
OnPropertyChanged(nameof(SomeValue));
}
}
}

protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

Bind it to your view:

var searchBar = new SearchBar();
searchBar.SetBinding(SearchBar.TextProperty, new Binding("SearchText", BindingMode.TwoWay));

If you need to retrieve your view model on some action:

var viewModel = BindingContext as ViewModel;
// update your viewModel then reassign to BindingContext
BindingContext = viewModel;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.