Hassan Abdul-Kareem
Hassan Abdul-Kareem

Reputation: 27

c# MVVM wpf design passing data between viewmodel and view methods

I am not sure if I am quite catching the idea behind the MVVM design specially regarding passing the data from viewmodel -> view and vice versa.

So for example let's say I have a model that has those properties (As simple as possible) :

public class User{

public string username {get; set;}
public string password {get; set;}
}

and here's my ViewModel that has a login method:

 // dependency injection
private readonly Context _context;
public constructor(Context context)
{
    _context = context;
}
// my method to verify login:

public async Task<bool> login(string username, string password)
{
    // fetching data
    var user = await _context.Users.FirstOrDefaultAsync(p => p.username== username&& p.Password == password);
    return (user != null);
 }

so my question is: how should I deliver these methods to the view class?

I usually just do this inside the button_click():

Var viewmodel = new Viewmodels.User();
login_state = viewmodel.login(email, password);

However I just feel this isn't the right way as it'd make the design very tightly coupled. How should I implement it?

Upvotes: 0

Views: 1761

Answers (2)

A.D.
A.D.

Reputation: 26

First make sure your viewmodel is set as DataContext or it is accessible from it.

public SomeView(SomeViewModel vm)
{
    DataContext = vm;
    InitializeComponent();
}

Now your viewmodel is accessible from XAML:

<Button Command="{Binding LoginCommand}">

Create command in viewmodel:

class SomeViewModel
{
    private readonly Context _context;

    public SomeViewModel(Context context)
    {
       _context = context;
    }

    public ICommand LoginCommand => new RelayCommand(LoginAndStuff);

    private void LoginAndStuff(object param)
    {
        // do stuff here
    }
}

How to RelayCommand => this link

Upvotes: 1

RichyP7
RichyP7

Reputation: 29

You have to use Bindings for displaying your user. For calling actions from the view you can use Commands. They can be bound in your ViewModel. (Why RelayCommand) Try to think about testing your code. If you are using your viewobjects in the testcode you will face a lot of problems. MVVM helps you to seperate your view completely. If you strictly seperate vm and view you will have an easy life for unittesting.

Upvotes: 0

Related Questions