0

I'm currently developing an app in WPF using the MVVM pattern ( without framework ). I use VS2019, Each view is an UserControl The app is connected to a local database MySQLLite.

When I start my program, I have an user connection. When the user connection is successful, it loads my object "Engine" in my global class "BaseViewModel" ( inherit all ViewModel ).

In WinForm when I create a new Form(View), I just transfer my Engine class in parameters and I save the Engine locally in my Form ( not null ) and then I have access to my value in Engine like User.

What is the best way to do it in WPF using MVVM?

I try to transfer the Engine to my ViewModel when I create but it always overwrites it later with null. Because it opens the view without parameter later and calls my constructor without parameter.

ASh
  • 34,632
  • 9
  • 60
  • 82
  • You realise you can bind to a static and that could implement inotifypropertychanged? If it needs to be instantiated you could potentially make it a resource in application.current.resources. – Andy Mar 05 '20 at 12:11
  • Idont really understand this point. For me static contain only default value like connection string or name or global setup. Or you want me to copy my loaded user into the static class ? –  Mar 05 '20 at 12:15
  • if some object is to be shared across an entire application then your candidates to achieve that aim include: dependency injection, a static, resources or some sort of mediator. – Andy Mar 05 '20 at 14:54

1 Answers1

0

You can create Data Access Level class to load your engine from DB. For example, it will be named EngineDataAccess and it will have GetEngine() method. Next in your EngineViewModel you can implement something like this:

private readonly Engine engine;

public string EngineName
{
   get {return engine.Name; }
   set {engine.Name = value; OnPropertyChanged("EngineName");}
}


public EngineViewModel(EngineDataAccess engineDataAccess)
{
    engine = engineDataAccess.GetEngine();
}

In your code:

EngineDataAccess engineDataAccess = new EngineDataAccess();
EngineViewModel engineViewModel = new EngineViewModel(engineDataAccess);
form.DataContext = engineViewModel;

What is not very good in this way and how it can be done better: 1) getting engine from db on creating view model process => it will be better to do it on Load view model (MVVM load data during or after ViewModel construction?) 2) using EngineDataAccess class instead of interface 3) binding datacontext in the codebehind => better to use IoC

Also, I would recommend you to use some MVVM framework like Galasoft.MVVM. It does MVVM using simpler.

AnnaS
  • 76
  • 4
  • Could you give me a vote to improve my notation. I get banned and I don't really understand why. I'm trying to improve myself, please help me out, thanks in advance ;) –  Nov 15 '20 at 23:49