-
Notifications
You must be signed in to change notification settings - Fork 37
EventToCommandBehavior
The EventToCommandBehavior
is a Xamarin.Forms behavior that allows you to connect a .NET event exposed by a visual in XAML to an ICommand
property on a ViewModel or other binding source.
It will automatically pull the BindingContext
from the associated control unless you specifically set the BindingContext
yourself.
You must supply two values:
-
EventName
: the name of the .NET event to connect to. -
Command
: theICommand
implementation to forward the event to.
By default, no parameter is passed to the command (e.g. null
). However, two additional properties can be set to control this behavior.
-
CommandParameter
: a specific bindable property which provides a value to pass as the command parameter. -
EventArgsConverter
: anIValueConverter
implementation which is passed thesender
andEventArgs
from the event and returns some object to use as the command parameter.
EventArgsConverter
overrides CommandParameter
- so if the former is set, the latter will not be used.
There is a built-in value converter EventArgsConverter which can pull out a single property or field from a class and return it. For example to the retrieve the Item
from the ItemTappedEventArgs
. Alternatively, you can create your own IValueConverter
as shown below.
In the following example, the MyCommand
command would be located on the BindingContext
of the associated Label
.
<Page xmlns:inf="clr-namespace:XamarinUniversity.Infrastructure;assembly=XamU.Infrastructure" ...>
...
<Label Text="{Binding Text}" ...>
<Label.Behaviors>
<inf:EventToCommandBehavior
EventName = "SizeChanged" Command="{Binding MyCommand}"
EventArgsConverter="{StaticResource converter}"/>
</Label.Behaviors>
</Label>
The converter would look like this:
// Convert SizeChanged event into `Size` object
class SizeChangedValueConverter : IValueConverter
{
public object Convert (object value, Type targetType, object parameter, CultureInfo culture)
{
// value = sender
// parameter = EventArgs
View v = (View)value;
return new Size { Height = v.Height, Width = v.Width };
}
public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException ();
}
}
By default, the EventToCommandBehavior
pulls the binding context from it's associated object. However, you might need to change that - you can use the RelativeBindingContext class to do this (and keep it synchronized).
<Page xmlns:inf="clr-namespace:XamarinUniversity.Infrastructure;assembly=XamU.Infrastructure"
x:Name="Root" ...>
...
<Label Text="{Binding Text}" ...>
<Label.Behaviors>
<inf:EventToCommandBehavior BindingContext="{RelativeBindingContext Root}" ... />
</Label.Behaviors>
</Label>
In this example, the binding context would be set to whatever the Page
binding context is.