首页 > 解决方案 > 自定义 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}相同的结果或进行交互,该命令将使它

标签: xamarinxamarin.android

解决方案


从你写的,我假设你有一个使用你的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事件(请参阅文档)更具表现力,并且为您节省了额外的命令。


推荐阅读