简体   繁体   中英

Correct way to implement MVVM Design pattern when using SQLite

So lets say I have a SQLite database of Person's with property Name

Public Class Person
{

    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
}

And now I have a view with a ListBox Displaying those names

<ListBox ItemSource={Binding People}>
    <ListBox.ItemTemplate>
        <DataTemplate>
           <Label Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

and my Views DataContext is PeopleViewVM

Public Class PeopleViewVM
{
     Public PeopleViewVM
     {
       //Do my SQLite stuff,
       // Get IEnumerable Person's
       // Create Observable Collection of People
     }

        private ObservableCollection<Person> _people;
        public ObservableCollection<Person> People
        {
            get { return _people; }
            set 
            { 
                _people = value;
                RaisePropertyChanged();
            }
        }
}

Now I understand this is a simple example. But I am unsure whether this is the correct implementation of the MVVM design pattern. If Person my model this means that the view is binding directly to the model when it is binding to the property name . If I change the name of a person in code behind this won't be reflected in the view. What is the correct way to do this example using the MVVM design pattern?

That can be the "correct" implementation, based on your requirements. I wouldn't say that there's a "correct", and "incorrect" for this issue. More like: would it be better for my scenario, or not?

People choose to bind models against view directly based on their requirements, and how they feel. Sometimes I like to simplify my models, and wrap them into "PersonViewModel", in order to expose more relevant properties, and not pollute the Model .

If that doesn't suit you, you can download ReSharper(takes care of "trying" to keep the View & viewmodel synchronized), or alternatively you can encapsulate your model further, and create a "proxy" object, as such:

Public Class PersonViewModel
{
     readonly Person _person;

     Public PersonViewModel(Person person)
     {
       _person = person;
     }

   public string Name
   {
       get { return _person.Name; }
       set 
       { 
           _person.Name = value;
           RaisePropertyChanged();
       }
   }

which seems to be pointless, but helps to keep the view and model even more separate, in case of model entities that change often. ReSharper does take care of most cases, in my experience.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM