This is a simple sample of how to bind to the click event of a button.
The xaml (of the view)
I created a simple page with a button on it. Note the Command="{Binding Click}". This binds the click event to a property on the ViewModel that has the name Click.
xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MvvmSample.MainPage">
<Button Command="{Binding Click}"
Text="Click me!"
VerticalOptions="Center"
HorizontalOptions="Center" />
</ContentPage>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MvvmSample.MainPage">
<Button Command="{Binding Click}"
Text="Click me!"
VerticalOptions="Center"
HorizontalOptions="Center" />
</ContentPage>
The ViewModel
This is what we bind to, a property called click that returns an object implementing ICommand.
using System.Diagnostics;
using System.Windows.Input;
using Xamarin.Forms;
namespace MvvmSample.ViewModels
{
public class MainPageViewModel
{
public ICommand Click
{
get {
return new Command (() => {
Debug.WriteLine ("Click");
});
}
}
}
}
using System.Windows.Input;
using Xamarin.Forms;
namespace MvvmSample.ViewModels
{
public class MainPageViewModel
{
public ICommand Click
{
get {
return new Command (() => {
Debug.WriteLine ("Click");
});
}
}
}
}
The View (code behind)
This is the file you want to keep as light as possible. Just create the ViewModel and assign it to the BindingContext. You should have some sort of dependency injection to abstract the creation of the ViewModel away. But this is just a simple sample.
using MvvmSample.ViewModels;
using Xamarin.Forms;
namespace MvvmSample
{
public partial class MainPage : ContentPage
{
public MainPage ()
{
InitializeComponent ();
BindingContext = new MainPageViewModel ();
}
}
}
using Xamarin.Forms;
namespace MvvmSample
{
public partial class MainPage : ContentPage
{
public MainPage ()
{
InitializeComponent ();
BindingContext = new MainPageViewModel ();
}
}
}
To sum up
- Keep the code-behind to a minimum
- ALWAYS databind your events, don't wire up event handlers in your code behind. This forces all logic to belong the the ViewModel, not the view. Just the way we like it! :)
No comments:
Post a Comment