xamarin - 自定义 ViewCell 包含按钮具有命令并绑定到此命令
问题描述
ViewCell
我修复了一些项目中的一些问题,其中一个我需要在分离的类和文件中使用自定义,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="HBRS.Controls.ViewCellTemplates.ArticleItemViewCell">
<Image>
<Image.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding BindingContext.clickCommand, Source={x:Reference Name=mArt}}"
CommandParameter="{Binding .}" />
</Image.GestureRecognizers>
</Image>
</ViewCell>
mArt
将命令用它做一些事情的视图在哪里
之后,我在我的xamarin
页面中使用了这个视图单元,如下所示:
<ListView.ItemTemplate>
<DataTemplate>
<Cell:ArticleItemViewCell />
</DataTemplate>
</ListView.ItemTemplate>
当我在我的设备上运行应用程序时,它会抛出一个异常,说找不到为“mArt”引用的对象,
所以我需要一些方法来传递Source={x:Reference Name=mArt}
相同的结果或进行交互,该命令将使它
解决方案
从你写的,我假设你有一个使用你的ViewCell
东西的观点
<ContentView ...
x:Name="mArt">
<ListView ...>
<ListView.ItemTemplate>
<DataTemplate>
<templates:ArticleItemViewCell ... />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentView>
现在你正试图mArt
从你的ViewCell
. 不幸的是,事情并非如此。mArt
不是全局变量,而是视图类的成员(如果您对细节感兴趣,请查看.xaml.g.cs
在您的对象文件夹中创建的文件)。
ArticleItemViewCell
然而是一个不同的类,你不能简单地访问其他类的字段。ArticleItemViewCell
什么都不知道mArt
。虽然可能以某种方式访问父级,但我建议您不要这样做,因为您往往会忘记这些细节,几个月后您会查看您的视图并想知道与单元格的交互是在哪里实现的,直到你意识到,细胞做了一些可疑的事情。它只会花费你时间。去过也做过。相信我。
而是在您的视图单元中创建一个类型的可绑定属性Command
,并从您的包含视图绑定到它
在 ArticleItemViewCell.xaml.cs 中
public static readonly BindableProperty TappedCommandProperty = BindableProperty.Create(nameof(TappedCommand), typeof(Command), typeof(ArticleItemViewCell));
public Command TappedCommand
{
get => (Command)GetValue(TappedCommandProperty);
set => SetValue(TappedCommandProperty, value);
}
现在你可以从你的ArticleItemViewCell
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="HBRS.Controls.ViewCellTemplates.ArticleItemViewCell"
x:Name="Cell">
<Image>
<Image.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding TappedCommand, Source={x:Reference Cell}}"
CommandParameter="{Binding .}" />
</Image.GestureRecognizers>
</Image>
</ViewCell>
从您的角度来看,您可以绑定clickCommand
您的虚拟机
<ContentView ...
x:Name="mArt">
<ListView ...>
<ListView.ItemTemplate>
<DataTemplate>
<templates:ArticleItemViewCell TappedCommand="{Binding Source={x:Reference mArt}, Path=BindingContext.clickCommand}" ... />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentView>
我没有尝试确切的代码,但基本上这应该可以工作。
请注意:使用事件来命令行为(请参阅此处)使用ItemTapped
事件(请参阅文档)更具表现力,并且为您节省了额外的命令。
推荐阅读
- javascript - url 行的正则表达式
- java - 如果 Spring Boot 失败,如何停止重新尝试与 RabbitMq、Postgress 建立连接?
- amazon-web-services - ec2 中的 CPU 使用率突然达到 99%
- postgresql-12 - 跨 postgresql-8 和 postgresql-12 在 bytea 中存储字符串的行为
- python - 在 sympy 中分离偏微分方程中的变量
- reactjs - 如何知道一个反应链接组件已被点击
- amazon-web-services - 从没有 EC2 的本地计算机访问 AWS RDS
- node.js - 错误:无法读取未定义的属性“请求”
- java - OAuth2 授权码已兑换,请使用新的有效代码重试或使用现有的刷新令牌
- double - double 和 float 有什么区别