Xamarin – When/Why use command
Here’s a couple short features, but you really want to do more reading on the topic of commands because there is a bunch more to know that can be covered in a thread post. This is just my ‘major benefits’ explanation.
Commands are less coupled than events. Think of them as the next evolution of the Event.
For example, on an event you have to subscribe directly to that instance.
MyClassInstance.SomeEvent += eventHandlerMethod();
Which most times means you have to know the subscribscription at design time
But a command can be referenced just by name, including in your XAML binding. Meaning its more fluid and will bind to your context at RUNTIME.
1 2 3 4 5 6 7 8 |
<Button HeightRequest="55" Margin="0,7,0,0" VerticalOptions="CenterAndExpand" BackgroundColor="Green" Command="{Binding AcceptThisCommand}" CommandParameter="{Binding SelectedDocument}" FontSize="{StaticResource MediumFontSize}" IsVisible="{Binding IsSomethingDoneProperty, Converter={StaticResource BoolInvertConverter}}" Text="{StaticResource Accept}" TextColor="{StaticResource SecondaryTextColor}" Style="{StaticResource ButtonStyleLrg}" /> |
Commands can also take Parameters that again, don’t have to be defined at design time. So you can send virtually any run-time object along with the command, and let the handler be concerned with how to interpret it. In the eample above when the command is raised it will carry with it the SelectedDocument
as a parameter. So while you are clicking a button you are not subscribing to the Button.Click then forced to jump through hoops to handle some specific object. Instead the handler for “AcceptThis” receives the actual document to be accepted. The same command handler can then also be assigned to a menu item… Or ListView selection… Or a network call where a document is downloaded and should then be automatically accepted. All of those other options don’t have to know where the command was defined. All of those other options don’t have to provide the same parameter object.
When you put all that together it means an ‘AcceptThisCommand’ can be bound to a photograph in one case and have a photo processor handle it… and bound to a music file in another case and since the handler is from a different context it will know how to handle that data type.
And without the tight binding that events have you can add a new listener FROM the listener without having to know who/where the command is being raise from. You don’t have to to know that the FileDoneDownloadingCommand
is burried deep in ApplicationVM.Media.Handlers.REST.Services.Transfers
– You just know that you’re listening for the command to be raised. Later when someone refactors that service moving the command to a much easier to remember location all of the subscribers to don’t break. Making it a far more maintainable architecture.