Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it's not good to expose Model through ViewModel in Silverlight MVVM?

As far as I develop WPF application with MVVM, I never expose model through viewmodel's public property. Anyway, after I just come to world of Silverlight and WCF RIA I found new method to achieve data validation, that's being said by Required attribute. (there are others attributes as well)

This time instead of create validation logic inside viewmodel, I can do almost of validation logic inside the model itself.

public class TestUserPM {
    [Key]
    public int ID { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string Email { get; set; }
}

After that, all I need in ViewModel is expose public property of TestUserPM's type and let View binding directly to the model.

I think this is not elegant solution but it can work and it has no need to create tedious validation inside viewmodel property.

Are there any down-sides of this method?

Update 1

I just found 1 down-side, may be it has solution out there. I want to binding Button's Command, for example, button save to Command in ViewModel but this button can execute if and only if all informations is valid. From my experience with WPF MVVM which I've helper class I'll call OnCanExecuteChanged() inside public string this[string columnName] of IDataErrorInfo.

How can I handle with this kind of requirement?

like image 517
Anonymous Avatar asked Nov 04 '10 11:11

Anonymous


1 Answers

I expose Model through ViewModel all the time, just to keep things simple and to not repeat myself (DRY).

The only thing to avoid the need to add properties in the model to adapt to the UI (as Benjamin notes), is to keep the model as a propery of the viewModel, so you can add properties to the viewModel, without messing the model.

ie: The ViewModel is the DataContext and it has a Model property returning the model

<TextBlock Text={Binding Path=Model.Name} />
<TextBlock Text={Binding Path=Model.Address} />
like image 197
Eduardo Molteni Avatar answered Jan 19 '23 06:01

Eduardo Molteni