繁体   English   中英

.NET MAUI 带有命令和参数的自定义控件

[英].NET MAUI Custom control with command and parameters

我使用 4 个按钮和一个命令创建自定义控件。 这个命令,我使用工具包中的EventToCommandBehavior订阅了PressedReleased事件。

        <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>          

对于 CommandParameter,我希望我们的类具有 2 个属性。 我如何为我班级的每个按钮对象设置不同的值?

您可以使用数据绑定来设置CommandParameter 我分享一个例子:

假设有两个参数:方向和状态。 您可以生成如下所示的 MoveControlEventArgs:

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

然后在ViewModel中,生成MoveEventArgs实例

public MoveEventArgs Para1 { get; set; }

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

然后在.xaml文件中:

<Button.Behaviors>
    <toolkit:EventToCommandBehavior

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

对于 MoveCommand,我们可以检索参数,如以下代码:

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

希望对你有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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