C#-绑定手势识别器

我正在尝试在Xml中绑定手势识别器,以便单击项目时可以处理

我尝试将其用于XML

<DataTemplate x:Key="TextPostTemplate">
            <ViewCell>
                <StackLayout BackgroundColor="White" Margin="10, 10, 10, 10" Padding="10, 10, 10, 10">
                    <StackLayout Orientation="Horizontal">
                        <Label Text="{Binding Name}" TextColor = "Black" FontSize = "15"/>
                        <Image Source="options_icon.png" HeightRequest="15" HorizontalOptions="EndAndExpand" Margin="0, 0, 10, 0">
                            <Image.GestureRecognizers>
                                <TapGestureRecognizer Tapped="{Binding OptionClick}"/>
                            </Image.GestureRecognizers>
                        </Image>
                    </StackLayout>
                    <Label Text="{Binding Body}" TextColor = "Black"/>
                </StackLayout>
            </ViewCell>
        </DataTemplate>

我尝试将其绑定到

 foreach (var post in posts)
        {
      TapGestureRecognizer optionsClick = new TapGestureRecognizer();
            optionsClick.Tapped += (s, e) =>
            {
                ShowPostOptions(page, navigation, post.id, post.user);
            };
}

和…

OptionClick =选项点击

但是我明白了

.xaml : error : Unable to cast object of type ‘Xamarin.Forms.Xaml.ElementNode’ to type ‘Xamarin.Forms.Xaml.ValueNode’.

解决方法:

您的代码无法正常运行,因为您已将TapGestureRecognizer实例有效地绑定到了Tapped事件.您无法对事件进行数据绑定,而且如果要设置它,则将其设置为事件处理程序,而不是TapGestureRecognizer本身的实例.

您有两个选项-事件处理程序或命令.

事件处理程序

在XAML中声明手势识别器,如下所示:

<TapGestureRecognizer Tapped="TappedHandler" />

在页面的代码后面创建一个名为TappedHandler的事件处理程序:

public void TappedHandler(object sender, EventArgs e)
{
   ShowPostOptions(page, navigation, post.id, post.user);
}

命令

在XAML中声明手势识别器,如下所示:

<TapGestureRecognizer Command="{Binding TapCommand}" />

并在视图模型中创建一个命令,该命令将处理点击:

private ICommand _tapCommand;

public ICommand TapCommand => _tapCommand ?? 
     ( _tapCommand = new Command( 
          () => ShowPostOptions(page, navigation, post.id, post.user) ) );
上一篇:c#-Xamarin.Forms在运行时加载XAML视图


下一篇:windows定时执行百度新闻爬虫