Reputation: 185
I want to bind my entry and my label to a class inside my view model, so whenever my entry changes, my label and my class inside view model also changes
here is my code
Model
public class MyModel
{
public string Name { get; set; }
public string Description { get; set; }
}
View Model
public class MyViewModel : INotifyPropertyChanged
{
public MyViewModel()
{
Model = new MyModel();
}
private MyModel _Model;
public MyModel Model
{
get { return _Model; }
set
{
_Model = Model;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
BehindCode
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
BindingContext = new MyViewModel();
}
}
PAGE
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="RKE.Page1">
<StackLayout>
<Label Text="{Binding Model.Name}"/>
<Entry Text="{Binding Model.Name}"/>
</StackLayout>
</ContentPage>
Upvotes: 0
Views: 1170
Reputation: 1985
You need to implement INotify for model also
public class MyModel:INotifyPropertyChanged
{
string _name;
string _description;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get => _name;
set
{
_name = value;
OnPropertyChanged();
}
}
public string Description
{
get => _description;
set
{
_Description = value;
OnPropertyChanged();
}
}
void OnPropertyChanged([CallerMemberName]string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
Upvotes: 1