c# - 绑定(bind)手势识别器

标签 c# xml xaml xamarin xamarin.forms

我正在尝试在 Xml 中绑定(bind)一个手势识别器,这样我就可以在单击项目时进行处理

我尝试将其用于我的 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>

我试着把它绑定(bind)到

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

和...

OptionClick = optionsClick

但是我明白了

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

最佳答案

您的代码不起作用,因为您有效地将 TapGestureRecognizer 的实例绑定(bind)到 Tapped 事件。您不能对事件进行数据绑定(bind),而且如果要设置它,您会将其设置为事件处理程序,而不是 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}" />

然后在你的 View 模型中创建一个命令来处理点击:

private ICommand _tapCommand;

public ICommand TapCommand => _tapCommand ?? 
     ( _tapCommand = new Command( 
          () => ShowPostOptions(page, navigation, post.id, post.user) ) );

关于c# - 绑定(bind)手势识别器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48697549/

相关文章:

java - Hello World Android 应用程序,错误 : workspace\appcompat_v7\res\values-v21\styles_base. xml 找不到与给定名称匹配的资源

c# - 从字符串 C# 中返回值的一部分

xml - 如何以 slice 格式解析XML

c# - 在 C# 中返回没有后代的 XElement

xaml - 实现 ListView 的 float 操作按钮bottom_right - Xamarin.forms

c# - 如何在绑定(bind)到 ObservableCollection 时禁用 DataGrid 中的单元格

silverlight - WP7应用程序的反馈表

c# - 重写 ef core 2.1 中的相关子查询

c# - 在用 C# 加密的 SQL Anywhere 16 中解密 AES,反之亦然

javascript - 使用 swal 警报将 mvc 表单提交到带有参数的函数