Xamarin.Forms : How to set 'GestureRecognizers

2019-08-27 15:11发布

问题:

This might be a stupid question but I just wanted to know as I am new to Xamarin.forms.

Can we set 'GestureRecognizers' in Style. For example I want to create a style for lable like below...

<Style TargetType="Label" x:Key="LabelStyle">

    <Setter Property="GestureRecognizers">
        <Setter.Value>
            <TapGestureRecognizer Command="{Binding EditSectionCommand}"/>
        </Setter.Value>
    </Setter>
</Style>

but it shows an compile time error 'Can't resolve GestureRecognizers on Label'.

Any help is appreciated.

回答1:

You can't set this GestureRecognizers property in the style. Because GestureRecognizers is not a bindable property in the default Label.

If you do want to use Style to configure the TapGestureRecognizer, you can try to construct a customized label. Define a bindable command property which handles the TapGestureRecognizer event of the label:

public class CustomLabel : Label
{
    public ICommand MyCommand
    {
        get
        {
            return (ICommand)GetValue(MyCommandProperty);
        }
        set
        {
            SetValue(MyCommandProperty, value);
        }
    }
    public static readonly BindableProperty MyCommandProperty = BindableProperty.Create(nameof(MyCommand), typeof(ICommand), typeof(CustomLabel), null,
                                                                propertyChanged: (bindable, oldValue, newValue) =>
                                                                {
                                                                    // Add a Tap gesture to this label, and its command is the bindableproperty we add above 
                                                                    var control = (CustomLabel)bindable;
                                                                    control.GestureRecognizers.Clear();

                                                                    TapGestureRecognizer tap = new TapGestureRecognizer();
                                                                    tap.Command = newValue as ICommand;
                                                                    control.GestureRecognizers.Add(tap);
                                                                });
}

At last you can use this command in the XAML:

<ContentPage.Resources>
    <Style x:Key="LabelStyle" TargetType="local:CustomLabel">
        <Setter Property="MyCommand" Value="{Binding TapCommand}"/>
    </Style>
</ContentPage.Resources>