mardi 17 octobre 2023

Maui syntax to use converter inside of a C# method

What I'm trying to accomplish

In a CollectionView, I display a list of objects. In each display there's a checkbox next to it.

Ideally, when the user checks or un-checks the checkbox I go into a method where I can do stuff with the object:

enter image description here

The above is fantasy code.

The actual code

In reality, when the user checks/unchecks the box the code goes into a method, only I'm passing this object CheckedChangedEventArgs into the method.

I need to convert that object ChcekedChangedEventArgs into a bool. (Note that I'm using the MvvM pattern, so I'm not working with code-behind.)
enter image description here

A kind soul gave me some code that will probably do the converting:

public class CheckedChangedArgsConverter : BaseConverterOneWay<CheckedChangedEventArgs, bool>
{
    public override bool DefaultConvertReturnValue { get; set; } = false;

    public override bool ConvertFrom(CheckedChangedEventArgs value, CultureInfo culture)
    {
        return value.Value;
    }
}

However, I don't know how to use the converter. It seems like I have two options here:

  1. Run the converter from the Xaml and have it run before the command AddRemoveFromList is called so I can pass in the converted Boolean, or
  2. Run the converter code from the C# class, something like this:
    enter image description here

The fact is, I have no idea how to do either. Can anyone help?

====================================================================

EDIT: the object CheckedChangedEventArgs getting passed into the C# method is ALWAYS null.

Here's my Checkbox code. I'm using the EventToCommandBehavior because it's the only thing I can think of to call a command from inside the Checkbox:

<CheckBox x:Name="checkBox"
          ScaleX="1.5"
          ScaleY="1.5"
          Color="#000063"
          HorizontalOptions="End">
    <CheckBox.Behaviors>
        <toolkit:EventToCommandBehavior EventName="CheckedChanged"
                                        Command="{Binding Source={x:Reference this}, 
                                                  Path=BindingContext.AddRemoveFromListCommand}"/>                                       
    </CheckBox.Behaviors>
</CheckBox>

I added x:TypeArguments to the Checkbox:

<CheckBox x:Name="checkBox"
          ScaleX="1.5"
          ScaleY="1.5"
          Color="#000063"
          HorizontalOptions="End">
    <CheckBox.Behaviors>
        <toolkit:EventToCommandBehavior
                x:TypeArguments="CheckedChangedEventArgs"
                                        EventName="CheckedChanged"
                                        Command="{Binding Source={x:Reference this}, Path=BindingContext.AddRemoveFromListCommand}" />
    </CheckBox.Behaviors>
</CheckBox>

And that did the trick.




Aucun commentaire:

Enregistrer un commentaire