C# Xamarin表单绑定到嵌套类
我想将我的条目和标签绑定到视图模型内的一个类,因此每当条目发生变化时,视图模型内的标签和类也会发生变化 这是我的密码 型号C# Xamarin表单绑定到嵌套类,c#,xaml,xamarin.forms,C#,Xaml,Xamarin.forms,我想将我的条目和标签绑定到视图模型内的一个类,因此每当条目发生变化时,视图模型内的标签和类也会发生变化 这是我的密码 型号 public class MyModel { public string Name { get; set; } public string Description { get; set; } } public class MyViewModel : INotifyPropertyChanged { public MyViewModel()
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));
}
}
查看模型
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));
}
}
落后代码
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>
您还需要为模型实现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));
}
有什么问题吗?我想在条目更改时更改标签和viewmodel。你能帮助我吗?