我想将我的条目和我的标签绑定到我的视图模型中的一个类,所以每当我的条目更改时,我的标签和我的类视图模型也会发生变化
这是我的代码
模型
public class MyModel
{
public string Name { get; set; }
public string Description { get; set; }
}
查看模型
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();
}
}
页
<?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>
答案 0 :(得分:1)
您还需要为模型实现INotify
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));
}