Skip to content

EventToCommandBehavior

Mark Smith edited this page Aug 26, 2016 · 5 revisions

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.

Parameters

You must supply two values:

EventName : the name of the .NET event to connect to. Command : the ICommand 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 : an IValueConverter implementation which is passed the sender and EventArgs 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.

Example

<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>
// Convert SizeChanged event into `Size` object
class SizeChangedValueConverter : IValueConverter
{
    public object Convert (object value, Type targetType, object parameter, CultureInfo culture)
    {
        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 ();
    }
}

Clone this wiki locally