操纵集合和视图模型模式
我对 WPF 比较陌生,并且我确信这是一个相对简单的问题。
我有我的基础数据对象,一个 Person:
class Person
{
public string Surname {get; set; }
public string Firstname {get; set; }
public List<Address> Addresses {get; }
}
我希望在我的 WPF 应用程序中显示和编辑这个对象。为此,我创建了一个在 xaml 中绑定的 ViewModel:
class PersonViewModel
{
public string Fullname {get; }
public ObservableCollection<AddressViewModel> Addresses {get; }
}
这很好,但在操作我的地址集合时除外,我无法弄清楚我应该做什么:
- 我应该添加方法
AddAddress
、RemoveAddress
等...到我的PersonViewModel
类,用于使用AddressViewModel
实例操作我的集合 - 我应该只添加实例吗
AddressViewModel
到我的Addresses
可观察集合
上面的两者看起来都有点混乱 - 有没有更好的方法来处理集合?
I'm relatively new to WPF, and I'm having trouble with what I'm fairly certain is a relatively simple problem.
I have my underlying data object, a Person:
class Person
{
public string Surname {get; set; }
public string Firstname {get; set; }
public List<Address> Addresses {get; }
}
And I wish to display and edit this object in my WPF app. To this end I've created a ViewModel that I bind to in my xaml:
class PersonViewModel
{
public string Fullname {get; }
public ObservableCollection<AddressViewModel> Addresses {get; }
}
This is fine, except when it comes to manipulating my Address collection, where I can't work out what I should be doing:
- Should I add methods
AddAddress
,RemoveAddress
etc... to myPersonViewModel
class for manipulating my collection with instances ofAddressViewModel
- Should I just add instances of
AddressViewModel
to myAddresses
observable collection
Both of the above seem a bit messy - is there a better way of dealing with collections?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议在您的 ViewModel 中添加命令。
例如,您将有一个 AddAddressCommand 和一个 RemoveAddressCommand。您可以将这些命令绑定到视图(例如,您可以将按钮绑定到 AddAddressCommand),该视图将执行 ViewModel 中的一个方法,该方法将添加到集合中。
(在上面的示例中,我使用 RelayCommand,这是一个实现 ICommand 的自定义类,您可以阅读有关此 RelayCommand 这里
另外附注:我不会创建一个 AddressViewModel 我只会有一个实现 INotifyPropertyChanged 的 AddressModel。除非您有显示,否则不需要另一个地址视图模型您的模型中不存在的逻辑。
I would recommend adding commands in your ViewModel.
For example, you would have a AddAddressCommand and a RemoveAddressCommand. you could bind these commands to the View (e.g. you could bind a button to the AddAddressCommand) that will execute a method in your ViewModel that will add to the collection.
(In the above example i'm using RelayCommand, this is a custom Class that implements ICommand, you can read more on this RelayCommand here
Also a side note: I wouldn't create an AddressViewModel I would Just have an AddressModel that implements INotifyPropertyChanged. There is no need to another address viewmodel unless you have display logic that is not in your model.