I have 2 ViewModels. One is called User (containing basic information, nothing fancy) and another called Group, which has as a property, an IEnumerable of User. This IEnumerable is backed by a dictionary (there are a lot of users, need to search them fast)
public class Group
{
#region Fields
private Dictionary<string, User> userLookup;
#endregion //Fields
public Group()
{
userLookup = new Dictionary<string, User>();
}
public User[] Users
{
get
{
return userLookup.Values.ToArray<User>();
}
set
{
foreach (var user in value)
{
if (!userLookup.ContainsKey(user.Login))
userLookup.Add(user.Login, user);
}
}
}
public bool AddUser(User user)
{
if (userLookup.ContainsKey(user.Login))
return false;
use开发者_如何转开发rLookup.Add(user.Login, user);
return true;
}
}
Now, The GroupViewModel class needs to add a new user, but all the GroupViewModel gets shown is UserViewModels, and the Add functionality only accepts type User. Currently i have an Internal function on the UserViewModel which exposes the underlying User object, i was just wondering if that defeated the purpose of using MVVM.
Thanks!
It was my understanding that in MVVM the purpose of the ViewModel was to provide the public data and interfacing for the view. So if the view requires the exposition of this data then no, I don't think this breaches MVVM, i think its quite inline with the framework. Though some of the more experienced developers might have more insight.
Also in your Users
property, you double up on your AddUser code in the setter.
set
{
foreach (var user in value)
AddUser(user);
}
Might be easier and save you having to change the setter if the conditions for entering a user change or become more complicated.
I think its ok as long as you are doing it through methods.
Look, what MVVM says is "Don't bind domain objects directly to View, Wrap them in View Model".
Methods are not used for binding, unless you are using ObjectDataProvider.
Another way, you can have GroupViewModel to hold dictionary of UserViewModel.
精彩评论