问题描述
这可能是一个愚蠢的问题,但我只是想知道,因为我是 Xamarin.forms 的新手.
This might be a stupid question but I just wanted to know as I am new to Xamarin.forms.
我们可以在样式中设置GestureRecognizers"吗?例如,我想为标签创建一个样式,如下所示...
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>
但它显示编译时错误无法解析标签上的 GestureRecognizers".
but it shows an compile time error 'Can't resolve GestureRecognizers on Label'.
感谢任何帮助.
推荐答案
您不能在样式中设置此 GestureRecognizers
属性.因为 GestureRecognizers
不是默认 Label 中的可绑定属性.
You can't set this GestureRecognizers
property in the style. Because GestureRecognizers
is not a bindable property in the default Label.
如果您确实想使用 Style 来配置 TapGestureRecognizer
,您可以尝试构建自定义标签.定义一个可绑定的命令属性来处理标签的 TapGestureRecognizer
事件:
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);
});
}
你终于可以在 XAML 中使用这个命令了:
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>
这篇关于Xamarin.Forms:如何在样式中设置“GestureRecognizers"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!