Reputation: 3301
Ever since I began learning about Xamarin.Forms
, I've read that MVVM
is the preferred architecture for this. This is all new to me, so please be patient.
At work, a typical application (either asp.net or Windows Forms) will include an event handler that calls a method and displays it into a UI control:
private void buttonShow_Click(object sender, EventArgs e)
{
Vendors.Sales carSales = new Vendors.Sales();
DataTable carsTable = carSales.SalesMade();
DatagridSales.datasource = carsTable;
}
carSales.SalesMade
is a method that exists somewhere that returns a list that I display in my UI. I don't know what carSales.SalesMade
is; I just know it returns a datatable
.
This exact same idea is what I want to apply to my beginner's mobile app. The problem is that I haven't found a simple working example that implements MVVM to this very simple functionality that I want to accomplish. Most of the examples I've found are so convoluted that they confuse more than they help.
So my question is: how can I implement MVVM in this example? It can be pseudocode; it doesn't need to build/compile. I just want to see what it would look like.
Upvotes: 2
Views: 489
Reputation: 446
So just to elaborate on Commands and how they work.
Take a simple login button example.
Your ViewModel will have a Command to handle the login button click like so:
public ICommand LoginCommand {get; set;};
The command needs an action to call when the command is fired.
So in your constructor, you could initialize the command with the following :
LoginCommand = new Command(Login);
The Login Action corresponds to a method you have in your ViewModel like so:
private void Login()
{
//do login stuff
}
Finally, in your View you Bind the command to your control in this case the login button:
<Button x:Name="loginButton" Command="{Binding LoginCommand}" Text="Login" />
Upvotes: 2
Reputation: 9990
The problem is that using event handlers is something that you shouldn't do in MVVM. You should bind the Command
to the button in this particular case.
Upvotes: 1