Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MVVM - using model in view model class

I would like to know what is correct using of model class in in view model. As MVVM I use Caliburn Micro.

First alternative.

Model class:

    public class CurrentUser : IDataErrorInfo
    {
        public string Nick { get; set; }
        public string Password { get; set; }
//...
    }

Using model in view model class:

[Export(typeof(ILogOnViewModel))]
public class LogOnViewModel : Screen
{
    public CurrentUser CurrentUser { get; set; }

    //bind on control in view
    public string CurrentNick
    {
        get { return CurrentUser.Nick; }
        set
        {
            CurrentUser.Nick = value;
            NotifyOfPropertyChange(() => CurrentNick);
        }
    }

    //bind on control in view
    public string CurrentPassword
    {
        get { return CurrentUser.Password; }
        set
        {
            CurrentUser.Password = value;
            NotifyOfPropertyChange(() => CurrentPassword);
        }
    }
}

Second alternative:

Model class:

    public class CurrentUser : IDataErrorInfo, INotifyPropertyChanged
    {


        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        public string Nick
        {
            get { return _nick; }
            set
            {
                _nick = value;
                NotifyPropertyChanged("Nick");
            }
        }

        public string Password
        {
            get { return _password; }
            set
            {
                _password = value;
                NotifyPropertyChanged("Password");
            }
        }
//...
    }

Using model class in view model class:

[Export(typeof(ILogOnViewModel))]
public class LogOnViewModel : Screen
{
    //bind on UI control
    public CurrentUser CurrentUser { get; set; }
}

1 Answers

The first alternative would be better, since it encapsulates your model better from the View.
But you should implement IDataErrorInfo and INotifyPropertyChanged on the ViewModel, since the ViewModel should be the object that notifies your user interface of changes and errors.

like image 54
Botz3000 Avatar answered Apr 10 '26 15:04

Botz3000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!