这可能是一个愚蠢的问题,但我只是想知道,因为我是Xamarin.forms的新手。
我们可以在Style中设置'GestureRecognizers‘吗?例如,我想为lable创建一个样式,如下所示...
<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”。
任何帮助都是非常感谢的。
发布于 2018-05-28 14:03:55
不能在样式中设置此GestureRecognizers
属性。因为在默认的标签中,GestureRecognizers
不是可绑定的属性。
如果您确实想使用Style来配置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>
https://stackoverflow.com/questions/50522856
复制相似问题