【问题标题】:Xamarin.Forms : How to set 'GestureRecognizers' in styleXamarin.Forms:如何在样式中设置“GestureRecognizers”
【发布时间】:2018-05-25 06:32:10
【问题描述】:

这可能是一个愚蠢的问题,但我只是想知道,因为我是 Xamarin.forms 的新手。

我们可以在 Style 中设置“GestureRecognizers”吗?例如,我想为标签创建一个样式,如下所示...

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

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

但它显示编译时错误“无法解析标签上的 GestureRecognizers”。

感谢任何帮助。

【问题讨论】:

  • 尝试创建一个继承自Label的自定义控件,并将您的TapGestureRecognizer添加到自定义控件中。

标签: xaml xamarin xamarin.forms xamarin.ios


【解决方案1】:

您不能在样式中设置此GestureRecognizers 属性。因为GestureRecognizers 不是默认Label中的可绑定属性。

如果您确实想使用样式来配置TapGestureRecognizer,您可以尝试构建自定义标签。定义一个可绑定的命令属性来处理标签的TapGestureRecognizer 事件:

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);
                                                                });
}

你终于可以在 XAML 中使用这个命令了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 2019-11-10
    相关资源
    最近更新 更多