Silverlight 命令 MVVM
我想“减少” ViewModel 类中的命令数量。 我有一个 ViewModel,其中包含 5 个以上的列表(使用 View 上的列表框进行呈现,并且我将 ObservableCollection 绑定到其 ItemSource 参数;还绑定 SelectedItem 属性),并且每个列表都应该有自己的“添加/删除”等按钮。
所以,它看起来像这样:
public class PersonViewModel : ViewModelBase
{
Person _Person;
private ObservableCollection<WorkPlaceViewModel> _WPlaces;
private ObservableCollection<LanguageViewModel> _Languages;
... other lists
private WorkPlaceViewModel _SelectedWorkPlaceView;
...
}
添加 5x2 命令使 ViewModel 有点大。我可以将一个字符串硬编码到 CommandParameter 并使用 ViewModel 中的 switch-case 来处理它,但这听起来像是黑客攻击。 :p 或者我应该为每个列表框创建一个删除命令,并将 SelectedItem 作为参数传递?
MVVM 中最好的方法是什么?
I'd like to 'reduce' the number of commands in my ViewModel class.
I have one ViewModel which contains 5+ lists (using Listboxes on View to presentate, and I'm binding an ObservableCollection to its ItemSource parameter; also binding the SelectedItem property), and each list should have its own Add/Remove/etc button.
So, it looks like this:
public class PersonViewModel : ViewModelBase
{
Person _Person;
private ObservableCollection<WorkPlaceViewModel> _WPlaces;
private ObservableCollection<LanguageViewModel> _Languages;
... other lists
private WorkPlaceViewModel _SelectedWorkPlaceView;
...
}
Adding 5x2 command makes the ViewModel a bit large. I could hardcode a string to the CommandParameter and handle it with a switch-case in my ViewModel but this sounds like hacking. :p
Or should I go with creating a Remove command for each listbox, and pass the SelectedItem as a parameter?
Whats the best way for this in MVVM?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么你的视图模型中有一组视图模型? PersonViewModel 应该完成什么任务。在我看来,您需要将视图分解为多个视图并将它们绑定到不同的视图模型。您的视图和视图模型应尽可能小,以减少耦合。
也就是说,我建议在每个可观察集合上添加/删除命令。正如您所猜测的,使用硬编码字符串很混乱。如果每个可观察集合都有自己的添加/删除,那么每个集合将允许不同的逻辑并且更易于维护。
您可以从 ViewModel 中发布更多代码并稍微描述一下该应用程序吗?这将帮助我们确定是否可以有更好的设计决策。
Why do you have a collection of viewmodels in your viewmodel? What is the PersonViewModel supposed to accomplish. It sounds to me like you need to break up your view into multiple views and bind them to different viewmodels. Your views and viewmodels should be as small as possible to reduce coupling.
That said, I would recommend commands for add/remove on each observable collection. Using a hardcode string is messy, as you guessed. If each observable collection has their own add/remove that will allow different logic for each collection and is more maintainable.
Can you post more code from your ViewModel and describe the app a bit? That will help us determine if there could be a better design decision.