简体   繁体   中英

.NET MAUI Custom control with command and parameters

I create my custom control with 4 buttons and one command. This command, I subscribed to events Pressed and Released using EventToCommandBehavior from toolkit.

        <Button x:Name="forward" Grid.Column="1">
            <Button.ImageSource>
                <FontImageSource
                    Color="{x:Binding TextColor}"
                    BindingContext="{x:Reference forward}"
                    FontFamily="icomoon"
                    Glyph="&#xe901;" />
            </Button.ImageSource>
            <Button.Behaviors>
                <toolkit:EventToCommandBehavior
                    Command="{Binding MoveCommand}"
                    EventName="Pressed" />
                <toolkit:EventToCommandBehavior
                    Command="{Binding MoveCommand}"
                    EventName="Released" />
            </Button.Behaviors>
        </Button>          

For CommandParameter I want us my class with 2 properties. How I can put for each button object of my class with different value?

You could use data bindings to set the CommandParameter . I share an example:

Suppose there are two parameters: Direction and State. You could generate a MoveControlEventArgs which is like:

public class MoveEventArgs : EventArgs
{
    public string Direction { get; set; }
    public string State { get; set; }
    public MoveEventArgs()
    {
    }
}

Then in the ViewModel, generate MoveEventArgs instance

public MoveEventArgs Para1 { get; set; }

public MainPageViewModel()
{
    Para1 = new MoveEventArgs() { Direction = "forward", State = "Pressed" };
}

Then in the.xaml file:

<Button.Behaviors>
    <toolkit:EventToCommandBehavior

        Command="{Binding MoveCommand}"
        CommandParameter="{Binding Para1}"
        EventName="Pressed" />
    <toolkit:EventToCommandBehavior
        Command="{Binding MoveCommand}"
        CommandParameter="{Binding Para2}"
        EventName="Released" />
</Button.Behaviors>

And for MoveCommand, we could retrieve the parameter, like the following code:

    public Command MoveCommand
    {
        get
        {
            return new Command<MoveEventArgs>((e) =>
            {
                if(e.State== "Pressed")
                {
                    Console.WriteLine("avc");
                }
                if (e.State == "Release")
                {
                    Console.WriteLine("vvv");
                }
            });
        }
    }

Hope it works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM