如何在视图模型命令方法中获取GestureRecognizer命令的参数?

时间:2018-08-06 12:14:34

标签: xamarin xamarin.forms

我有一个模板,用于检查Tap:

<Grid.GestureRecognizers>
   <TapGestureRecognizer Command="{Binding TapCommand, Source={x:Reference this}}" CommandParameter="{Binding TapCommandParam, Source={x:Reference this}}" NumberOfTapsRequired="1" />
   </Grid.GestureRecognizers>

在后端,我这样做是为了建立绑定:

    public static readonly BindableProperty TapCommandProperty =
        BindableProperty.Create(
            nameof(TapCommand),
            typeof(Command),
            typeof(GridTemplate),
            default(Command));

    public Command TapCommand
    {
        get { return (Command)GetValue(TapCommandProperty); }
        set { SetValue(TapCommandProperty, value); }
    }


    public static readonly BindableProperty TapCommandParamProperty =
        BindableProperty.Create(
            nameof(TapCommandParam),
            typeof(string),
            typeof(GridTemplate),
            default(string));

    public string TapCommandParam
    {
        get { return (string)GetValue(TapCommandParamProperty); }
        set { SetValue(TapCommandParamProperty, value); }
    }

我这样设置命令:

private ICommand openPageCmd;

    public ICommand OpenPageCmd => openPageCmd ?? (openPageCmd = new Command(() => OpenPage()));

    public void OpenPage()
    {
        // I need the parameter of the command here
    }

点击网格时会调用该命令,但是如何访问我想使用的参数

1 个答案:

答案 0 :(得分:2)

像这样声明您的命令:

private ICommand openPageCmd;

public ICommand OpenPageCmd => openPageCmd ?? (openPageCmd = new Command<string>((stringValue) => xx(stringValue)));

public void xx(string stringValue)
{
    var a = 0;
}