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; }
if (someValue!= value)
someValue= value;

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

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.

Loading Facebook Comments ...