我正在尝试在 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/