首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Xamarin.Forms :如何在样式中设置'GestureRecognizers‘

Xamarin.Forms :如何在样式中设置'GestureRecognizers‘
EN

Stack Overflow用户
提问于 2018-05-25 14:32:11
回答 1查看 1.2K关注 0票数 1

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

我们可以在Style中设置'GestureRecognizers‘吗?例如,我想为lable创建一个样式,如下所示...

代码语言:javascript
复制
<Style TargetType="Label" x:Key="LabelStyle">

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

但是它显示了一个编译时错误“Can‘t resolve GestureRecognizers on Label”。

任何帮助都是非常感谢的。

EN

回答 1

Stack Overflow用户

发布于 2018-05-28 14:03:55

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

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

代码语言:javascript
复制
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中使用此命令:

代码语言:javascript
复制
<ContentPage.Resources>
    <Style x:Key="LabelStyle" TargetType="local:CustomLabel">
        <Setter Property="MyCommand" Value="{Binding TapCommand}"/>
    </Style>
</ContentPage.Resources>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50522856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档