Skip to content
This repository was archived by the owner on May 1, 2024. It is now read-only.
This repository was archived by the owner on May 1, 2024. It is now read-only.

[Enhancement] Generic EventToCommandBehavior #953

@pictos

Description

@pictos

Summary

Today with our current EventToCommandBehavior implementation we can see some issue using strongly type arguments with Command<T> the workaround today is using T as object and that's a kinda bad-sh thing to do.
If we have an EventToCommandBehavior<TType> that inherits from our EventToCommandBehavior we will be able to force the parameter to be the TType and doesn't crash the application.

An example of this issue can be seen here #950

API Changes

Here's the full implementation so far.

public class EventToCommandBehavior<TType> : EventToCommandBehavior
{
    protected override void OnTriggerHandled(object sender = null, object eventArgs = null)
    {
	    var parameter = CommandParameter
		    ?? EventArgsConverter?.Convert(eventArgs, typeof(object), null, null)
		    ?? eventArgs;
    
	    if (parameter.GetType() != typeof(TType))
	    {
		    parameter = null; // not sure if this a good approach, but nulling it we prevent an InvalidCastException (I suppose)
		    parameter = Convert.ChangeType(parameter, typeof(TType));
	    }
    
	    var command = Command;
	    if (command?.CanExecute(parameter) ?? false)
		    command.Execute(parameter);
    }
}

Intended Use Case

Make this scenario works

Coffee selectedCoffee;
public Coffee SelectedCoffee
{
    get => selectedCoffee;
    set => SetProperty(ref selectedCoffee, value);
}

async Task Selected(Coffee coffee)
{
    if (coffee == null)
        return;

    await Application.Current.MainPage.DisplayAlert("Selected", coffee.Name, "OK");
    SelectedCoffee = null;
}

On XAML the usage will be

<xct:EventToCommandBehavior
    x:TypeArguments="model:Coffee"
    Command="{Binding SelectedCommand}"
    EventArgsConverter="{StaticResource ItemSelectedEventArgsConverter}"
    EventName="ItemSelected" />

Who Will Do The Work?

  • I am willing to take this on myself
  • Just putting this out there for someone to pick up

Metadata

Metadata

Assignees

Labels

a/behaviorsThis issue/PR is related to behaviorsfeature-requestA request for a new feature.in-progressActively being worked on.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions