Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mvvm model ViewModel

Tags:

c#

mvvm

wpf

It can be named MVVM model or not? Because View interacts with DataModel through ViewModelData. Does View should interact only with ViewModelData? I did read somewhere that right MVVM model should implement INotify in ViewModel not in Model. Is it right?

namespace WpfApplication135
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelData();
    }
}
public class ViewModelData
{
    public DataModel DM { get; set; }
    public ViewModelData()
    {
        DM = new DataModel();
    }
}
public class DataModel : INotifyPropertyChanged
{
    public int label;
    public int Label
    {
        get
        {
            return label;
        }

        set
        {
            label = value;
            RaisePropertyChanged("Label");
        }
    }
    public DataModel()
    {
        Action Update = new Action(Run);
        IAsyncResult result = Update.BeginInvoke(null, null);
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string info)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
    public void Run()
    {
        int i=0;
        while(true)
        {
            System.Threading.Thread.Sleep(2000);
            Label = ++i;
        }
    }
}
}

xaml

    <Grid>
    <Label Content="{Binding DM.Label}" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/>

</Grid>
like image 598
A191919 Avatar asked Dec 20 '22 00:12

A191919


1 Answers

The initial thought for MVVM was indeed that the View should not know (not depend on) the Model.

In practice this meant re-implementing all those Model properties in the ViewModel (see the light-yellow box in the picture below), a lot of work. And extra painful when your Model can easily implement INPC, for example when it is generated from a database schema. Entity Framework in database-first mode lets you inject the INPC code through the T4 templates.

The consensus quickly became that it is OK to forward a ViewModel.Model property and bind to that, just like your DM property. See the light-blue box in the picture.

The issue is visualized well in this picture, note the large number of arrows in the top right corner. They depict the various solutions for databinding and you can use any combination of them.

WPF LOB Apllication Layers - MVVM

like image 149
Henk Holterman Avatar answered Dec 28 '22 23:12

Henk Holterman