{"id":24273,"date":"2016-02-02T12:01:35","date_gmt":"2016-02-02T20:01:35","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=24273"},"modified":"2019-04-04T09:06:48","modified_gmt":"2019-04-04T16:06:48","slug":"turn-events-into-commands-behaviors","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/turn-events-into-commands-behaviors\/","title":{"rendered":"Turn Events into Commands with Behaviors"},"content":{"rendered":"<p>\t\t\t\tUtilizing data binding in mobile apps\u00a0can greatly simplify development by automatically synchronizing an app\u2019s data to its user interface with minimal set up. Previously, we looked at the <a href=\"https:\/\/blog.xamarin.com\/introduction-to-data-binding\/\">basics of\u00a0data binding<\/a>, and then explored some <a href=\"https:\/\/blog.xamarin.com\/advanced-data-binding-for-ios-android-and-windows\/\">more advanced data binding scenarios<\/a> where values are formatted and converted as they are passed between <em>source<\/em> and <em>target<\/em> by the binding engine. We then examined a Xamarin.Forms feature called <em>commanding<\/em>, that <a href=\"https:\/\/blog.xamarin.com\/simplifying-events-with-commanding\/\">allows data bindings to make method calls directly to a ViewModel<\/a>, such as when a button is clicked.<\/p>\n<p>In this blog post, let&#8217;s explore a Xamarin.Forms feature called <em>behaviors<\/em>, which in the context of\u00a0<em>commanding<\/em>, enables any Xamarin.Forms control to use data bindings to make method calls to a ViewModel.<\/p>\n<h2>Introduction to Behaviors<\/h2>\n<p>Behaviors\u00a0let you add functionality to UI controls without having to subclass them. Instead, the functionality is implemented in a behavior class and attached to the control as if it was part of the control itself. Behaviors enable you to implement code that you would normally have to write as code-behind because it directly interacts with the API of the control in such a way that it can be concisely attached to the control and packaged for reuse across more than one app. They can be used to provide a full range of functionality to controls, from adding an email validator to a <code>Entry<\/code> to creating a rating control using a tap gesture recognizer.<\/p>\n<h3>Implementing a Behavior<\/h3>\n<p>The procedure for implementing a behavior is as follows:<\/p>\n<ol>\n<li>Inherit from the <code>Behavior&lt;T&gt;<\/code> class, where <code>T<\/code> is the type of control that the behavior should apply to.<\/li>\n<li>Override the <code>OnAttachedTo<\/code> method and use it to perform any set up.<\/li>\n<li>Override the <code>OnDetachingFrom<\/code> method to perform any clean up.<\/li>\n<li>Implement the core functionality of the behavior.<\/li>\n<\/ol>\n<p>This results in the structure shown in the following code example:<\/p>\n<pre class=\"lang:c# decode:true \" title=\"CustomBehavior class\">public class CustomBehavior : Behavior&lt;View&gt;\n{\n\tprotected override void OnAttachedTo (View bindable)\n\t{\n\t\tbase.OnAttachedTo (bindable);\n\t\t\/\/ Perform setup\n\t}\n\n\tprotected override void OnDetachingFrom (View bindable)\n\t{\n\t\tbase.OnDetachingFrom (bindable);\n\t\t\/\/ Perform clean up\n\t}\n\n\t\/\/ Behavior implementation\n}<\/pre>\n<p>The <code>OnAttachedTo<\/code> method is fired immediately after the behavior is attached to the UI control. This method is used to wire up event handlers or perform another setup that\u2019s required to support the behavior functionality. For example, you could subscribe to the <code>ListView.ItemSelected<\/code> event and execute a command when the event fires. The behavior functionality would then be implemented in the event handler for the <code>ItemSelected<\/code> event.<\/p>\n<p>The <code>OnDetachingFrom<\/code>\u00a0method is fired when the behavior is removed from the UI control and is used to perform any required clean up. For example, you could unsubscribe from the <code>ListView.ItemSelected<\/code> event in order to prevent memory leaks.<\/p>\n<h3>Consuming a Behavior<\/h3>\n<p>Every Xamarin.Forms control has a behavior collection to which behaviors can be added, as shown in the following code example:<\/p>\n<pre class=\"lang:xml decode:true\" title=\"Consuming a behavior example\">&lt;Editor&gt;\n\t&lt;Editor.Behaviors&gt;\n\t\t&lt;local:CustomBehavior \/&gt;\n\t&lt;\/Editor.Behaviors&gt;\n&lt;\/Editor&gt;<\/pre>\n<p>At runtime, the behavior will respond to interaction with the control, as per the behavior implementation.<\/p>\n<h2>Invoking a Command in Response to an Event<\/h2>\n<p>In the context of <em>commanding<\/em>, behaviors are a useful approach for connecting a control to a command. In addition, they can also be used to associate commands with controls that were not designed to interact with commands. For example, they can be used to invoke a command in response to an event firing. Therefore, behaviors address many of the same scenarios as command-enabled controls, while providing a greater degree of flexibility.<\/p>\n<p>The <a href=\"https:\/\/github.com\/davidbritch\/xamarin-forms\/tree\/master\/ItemSelectedBehavior\" target=\"_blank\">sample application<\/a> contains the <code>ListViewSelectedItemBehavior<\/code> class, that executes a command in response to the <code>ListView.ItemSelected<\/code> event firing.<\/p>\n<h3>Implementing Bindable Properties<\/h3>\n<p>In order to execute a user specified command, the <code>ListViewSelectedItemBehavior<\/code> defines two <code>BindableProperty<\/code> instances, as shown in the following code example:<\/p>\n<pre class=\"lang:c# decode:true\" title=\"ListViewSelectedItemBehavior class\">public class ListViewSelectedItemBehavior : Behavior&lt;ListView&gt;\n{\n\tpublic static readonly BindableProperty CommandProperty = \n            BindableProperty.Create (\"Command\", typeof(ICommand), typeof(ListViewSelectedItemBehavior), null);\n\tpublic static readonly BindableProperty InputConverterProperty = \n            BindableProperty.Create (\"Converter\", typeof(IValueConverter), typeof(ListViewSelectedItemBehavior), null);\n\n\tpublic ICommand Command {\n\t\tget { return (ICommand)GetValue (CommandProperty); }\n\t\tset { SetValue (CommandProperty, value); }\n\t}\n\n\tpublic IValueConverter Converter {\n\t\tget { return (IValueConverter)GetValue (InputConverterProperty); }\n\t\tset { SetValue (InputConverterProperty, value); }\n\t}\n    ...\n}<\/pre>\n<p>When this behavior is consumed by a <code>ListView<\/code>, the <code>Command<\/code> property should be data bound to an <code>ICommand<\/code> to be executed in response to the <code>ListView.ItemSelected<\/code> event firing, and the <code>Converter<\/code> property should be set to a converter that returns the <code>SelectedItem<\/code> from the <code>ListView<\/code>.<\/p>\n<h3>Implementing the Overrides<\/h3>\n<p>The <code>ListViewSelectedItemBehavior<\/code> overrides the <code>OnAttachedTo<\/code> and <code>OnDetachingFrom<\/code> methods of the <code>Behavior&lt;T&gt;<\/code> class, as shown in the following code example:<\/p>\n<pre class=\"lang:c# decode:true\" title=\"ListViewSelectedItemBehavior class\">public class ListViewSelectedItemBehavior : Behavior&lt;ListView&gt;\n{\n    ...\n\tpublic ListView AssociatedObject { get; private set; }\n\n\tprotected override void OnAttachedTo (ListView bindable)\n\t{\n\t\tbase.OnAttachedTo (bindable);\n\t\tAssociatedObject = bindable;\n\t\tbindable.BindingContextChanged += OnBindingContextChanged;\n\t\tbindable.ItemSelected += OnListViewItemSelected;\n\t}\n\n\tprotected override void OnDetachingFrom (ListView bindable)\n\t{\n\t\tbase.OnDetachingFrom (bindable);\n\t\tbindable.BindingContextChanged -= OnBindingContextChanged;\n\t\tbindable.ItemSelected -= OnListViewItemSelected;\n\t\tAssociatedObject = null;\n\t}\n    ...\n}<\/pre>\n<p>The <code>OnAttachedTo<\/code> method subscribes to the <code>BindingContextChanged<\/code> and <code>ItemSelected<\/code> events of the attached <code>ListView<\/code>. The reasons for the subscriptions are explained in the next section. In addition, a reference to the <code>ListView<\/code> the behavior is attached to\u00a0is stored\u00a0in the <code>AssociatedObject<\/code> property.<\/p>\n<p>The <code>OnDetachingFrom<\/code> method cleans up by unsubscribing from the <code>BindingContextChanged<\/code> and <code>ItemSelected<\/code> events.<\/p>\n<h3>Implementing the Behavior Functionality<\/h3>\n<p>The purpose of the behavior is to execute a command when the <code>ListView.ItemSelected<\/code> event fires. This is achieved in the <code>OnListViewItemSelected<\/code> method, as shown in the following code example:<\/p>\n<pre class=\"lang:c# decode:true\" title=\"ListViewSelectedItemBehavior class\">public class ListViewSelectedItemBehavior : Behavior&lt;ListView&gt;\n{\n    ...\n\tvoid OnBindingContextChanged (object sender, EventArgs e)\n\t{\n\t\tOnBindingContextChanged ();\n\t}\n\n\tvoid OnListViewItemSelected (object sender, SelectedItemChangedEventArgs e)\n\t{\n\t\tif (Command == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tobject parameter = Converter.Convert (e, typeof(object), null, null);\n\t\tif (Command.CanExecute (parameter)) {\n\t\t\tCommand.Execute (parameter);\n\t\t}\n\t}\n\n\tprotected override void OnBindingContextChanged ()\n\t{\n\t\tbase.OnBindingContextChanged ();\n\t\tBindingContext = AssociatedObject.BindingContext;\n\t}\n}<\/pre>\n<p>The <code>OnListViewItemSelected<\/code> method, which is executed in response to the <code>ListView.ItemSelected<\/code> event firing, first executes the converter referenced through the <code>Converter<\/code> property, which returns the <code>SelectedItem<\/code> from the <code>ListView<\/code>. The method then executes the data bound command, referenced through the <code>Command<\/code> property, passing in the <code>SelectedItem<\/code> as a parameter to the command.<\/p>\n<p>The <code>OnBindingContextChanged<\/code> override, which is executed in response to the <code>ListView.BindingContextChanged<\/code> event firing, sets the <code>BindingContext<\/code> of the behavior to the <code>BindingContext<\/code> of the control the behavior is attached to. This ensures that the behavior can bind to and execute the command that\u2019s specified when the behavior is consumed.<\/p>\n<h3>Consuming the Behavior<\/h3>\n<p>The <code>ListViewSelectedItemBehavior<\/code> is attached to the <code>ListView.Behaviors<\/code> collection, as shown in the following code example:<\/p>\n<pre class=\"lang:xml decode:true\" title=\"Consuming the ListViewSelectedItemBehavior\">&lt;ListView ItemsSource=\"{Binding People}\"&gt;\n\t&lt;ListView.Behaviors&gt;\n\t\t&lt;local:ListViewSelectedItemBehavior Command=\"{Binding OutputAgeCommand}\" \n            Converter=\"{StaticResource SelectedItemConverter}\" \/&gt;\n\t&lt;\/ListView.Behaviors&gt;\n&lt;\/ListView&gt;\n&lt;Label Text=\"{Binding SelectedItemText}\" \/&gt;<\/pre>\n<p>The <code>Command<\/code> property of the behavior is data bound to the <code>OutputAgeCommand<\/code> property of the associated ViewModel, while the <code>Converter<\/code> property is set to the <code>SelectedItemConverter<\/code> instance, which returns the <code>SelectedItem<\/code> of the <code>ListView<\/code> from the <code>SelectedItemChangedEventArgs<\/code>.<\/p>\n<p>The result of the behavior being consumed is that when the <code>ListView.ItemSelected<\/code> event fires due to an item being selected in the <code>ListView<\/code>, the <code>OutputAgeCommand<\/code> is executed, which updates the <code>SelectedItemText<\/code> property that\u00a0the <code>Label<\/code> binds to. The following screenshots show this:<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-24275\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/ExecuteCommand.png\" alt=\"ExecuteCommand\" width=\"1280\" height=\"768\" \/><\/p>\n<h3>Generalizing the Behavior<\/h3>\n<p>It\u2019s possible to generalize the <code>ListViewSelectedItemBehavior<\/code> so that it can be used by any Xamarin.Forms control, and so that it can execute a command in response to <em>any<\/em> event firing, as shown in the following code example:<\/p>\n<pre class=\"lang:xml decode:true \" title=\"Consuming the ListViewSelectedItemBehavior\">&lt;ListView ItemsSource=\"{Binding People}\"&gt;\n\t&lt;ListView.Behaviors&gt;\n\t\t&lt;local:EventToCommandBehavior EventName=\"ItemSelected\" Command=\"{Binding OutputAgeCommand}\" \n            Converter=\"{StaticResource SelectedItemConverter}\" \/&gt;\n\t&lt;\/ListView.Behaviors&gt;\n&lt;\/ListView&gt;\n&lt;Label Text=\"{Binding SelectedItemText}\" \/&gt;<\/pre>\n<p>For more information, see the <code>EventToCommandBehavior<\/code> class in the <a href=\"https:\/\/github.com\/davidbritch\/xamarin-forms\/tree\/master\/ItemSelectedBehavior\" target=\"_blank\">sample application<\/a>.<\/p>\n<h2>Wrapping Up Behaviors<\/h2>\n<p>In the context of <em>commanding<\/em>, behaviors are a useful approach for connecting a control to a command. In addition, they can also be used to associate commands with controls that were not designed to interact with commands. For example, they can be used to invoke a command in response to an event firing. Therefore, behaviors address many of the same scenarios as command-enabled controls, while providing a greater degree of flexibility.<\/p>\n<p>For more information about behaviors, see our\u00a0<a href=\"https:\/\/developer.xamarin.com\/guides\/xamarin-forms\/working-with\/behaviors\/\">Working with Behaviors<\/a>\u00a0document.\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Utilizing data binding in mobile apps\u00a0can greatly simplify development by automatically synchronizing an app\u2019s data to its user interface with minimal set up. Previously, we looked at the basics of\u00a0data binding, and then explored some more advanced data binding scenarios where values are formatted and converted as they are passed between source and target by [&hellip;]<\/p>\n","protected":false},"author":543,"featured_media":24275,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[4,16],"class_list":["post-24273","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform","tag-xamarin-forms"],"acf":[],"blog_post_summary":"<p>Utilizing data binding in mobile apps\u00a0can greatly simplify development by automatically synchronizing an app\u2019s data to its user interface with minimal set up. Previously, we looked at the basics of\u00a0data binding, and then explored some more advanced data binding scenarios where values are formatted and converted as they are passed between source and target by [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/24273","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/543"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=24273"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/24273\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=24273"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=24273"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=24273"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}