Starting Xamarin with MVVM binding in Code

No Comments

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;

Categories: Xamarin