嘿,如果你有一个对象,例如Person
,其属性为FirstName
,LastName
,BirthDate
。你需要单独购买每个房产吗?
在ViewModel.cs中这样:
private string _FirstName;
public string FirstName
{
get { return _FirstName; }
set
{
_FirstName = value;
RaisePropertyChanged("FirstName");
}
}
这在View.xaml
中<TextBox Text="{Binding FirstName, Mode=TwoWay}" />
我试过了:
<TextBox Text="{Binding Person.FirstName, Mode=TwoWay}" />
因此我不需要键入每个属性。这可能吗?究竟是怎么回事?
答案 0 :(得分:0)
以下是一种模式:
<强>模型强>
public class Notifier : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Person : Notifier
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
RaisePropertyChanged(); //No need to pass "FirstName".
}
}
}
<强>视图模型强>
public class PersonViewModel : Notifier
{
private Person _person;
public Person Person
{
get { return _person; }
set
{
_person= value;
RaisePropertyChanged(); //No need to pass "Person".
}
}
}
查看(此视图的DataContext
被假定为PersonViewModel
类的实例)
<!-- other codes -->
<Grid DataContext="{Binding Person}">
<!-- other codes -->
<TextBox Text="{Binding FirstName, Mode=TwoWay}" />
<!-- other codes -->
</Grid>
<!-- other codes -->