我有以下模型:
public class Person
{
public string LastName{get;set;}
public City City {get;set;}
}
public class City
{
public string Name {get;set;}
}
我有两个观点:
一个 DataGrid(AllPersonsViewModel)
我的 AllPersonsViewModel:
public class AllPersonViewModel : ViewModel
{
public ObservableCollection<PersonViewModel> PersonViewModels {get;set;}
}
我从以下 PersonViewModel 开始:
public class PersonViewModel : ViewModel
{
private Person _person;
public string Name
{
get { return _person.Name;}
set { _person.Name = value; RaisePropertyChange("Name");}
}
public string CityName
{
get { return _person.City.Name;}
}
}
然后我添加了用于添加新人员的属性。在 View 中,我需要一个用于 PersonName 的文本框和一个用于选择城市的组合框:
public class PersonViewModel : ViewModel
{
private Person _person;
public string Name
{
get { return _person.Name;}
set { _person.Name = value; RaisePropertyChange("Name");}
}
public string CityName
{
get { return _person.City.Name;}
}
public City SelectedCity
{
get { return _person.City;}
set { _person.City = value; RaisePropertyChange("SelectedCity");}
}
public ObservableCollection<City> Cities {get;set;}
}
这是正确的方法吗?这对我来说似乎有点多余。在 AllPersonsView 的网格中,我还可以直接绑定(bind)到“SelectedCity.Name”而不是额外的属性 CityName。网格也是只读的。
最佳答案
你有多个问题;
1 - 您不需要在 AllPersonViewModel
中声明可观察的 View 模型集合.只需声明 Person
的 ObservableCollection .
2 - 不要添加 CityName
属性(property);正如您所说,不需要。
3-不要添加Name
属性(property)。将文本框绑定(bind)到 Person
的 Name 属性.
关于c# - WPF MVVM 设计 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14397609/