0

I'm fairly new to MVVM and I recently discovered that buttons could be bound to functions in classes as well.

So what I've been doing basically is authenticating usernames and passwords using Linq using the click event in the code behind like this:

private void Login_Click(object sender, RoutedEventArgs e)
    {
        var user = from u in MyDBDataSet.logins
                   where u.username == usernameTextBox.Text
                   && u.password == passwordPasswordBox.Password
                   select u;

        if (user.Any())
        {
            MessageBox.Show("Success, Credentials Found");
        }

        else
        {

            MessageBox.Show("Error, Nothing Found");
        }
    }

In order for me to use the MVVM pattern I'd end up having to do something like this right?

<!-- Create the binding in the xaml />
<Button Content="Login" Command="{Binding login}"/>

Set the data context in the code behind

public login()
    {
        InitializeComponent();

        // LoginSQL is the View Model class
        LoginSql = new SQL.content.authentication.login.loginSQL();
        DataContext = LoginSql;
    }

And in the View Model, create the property to bind the button to.

    private ICommand _login;
    public ICommand login
    {
        get;
        set;
    }

See this is where my knowledge of it is very limited. From looking around here, I got the understanding that I need to tell it under which conditions it can execute or the button will be greyed out when the app is run, and I should also tell it what to do when it executes.

At the moment that's what's failing me though. How do I hook up the method to log the user in to the ICommand property?

Offer
  • 630
  • 2
  • 11
  • 28

1 Answers1

0

You will need to create/obtain a common MVVM pattern base-class called DelegateCommand. Basically this class implements ICommand allows you to specify delegates for the Execute() and CanExecute() methods in the ICommand interface.

The PRISM Library contains an implementation of it and so does Kent Boogaart's blog

toadflakz
  • 7,764
  • 1
  • 27
  • 40