【问题标题】:Xamarin Forms - image tap handler for custom ViewCellsXamarin Forms - 自定义 ViewCells 的图像点击处理程序
【发布时间】:2017-05-29 06:17:03
【问题描述】:

我有一个带有自定义单元格的 ListView。在每个自定义单元格中,用户可以点击一个看起来像椭圆的图像来调用单元格中的功能。在这一点上,我专注于一个美学问题。

请注意,我已经使用包含带有省略号的图像的 Button 实现了这一点。我使用了 Button,因为它本机响应点击事件。问题是按钮有边框。此外,该按钮的点击动画效果不太理想。

<ListView x:Name="___listview" HasUnevenRows="True">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal" Padding="10" Margin="10">
                    <Button Image="{Binding ImageName}" Command="{Binding UpCount}" 
                            BackgroundColor="White" WidthRequest="50" />
                    <Label Text="{Binding Count}" HorizontalOptions="CenterAndExpand" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

每个 ViewCell 都绑定到以下模型。

public class Model : INotifyPropertyChanged
{
    public Model()
    {
        _count = 0;
        _imageName = "ellipses_vertical.png";
        UpCount = new Command(() =>
        {
            Count++;
            ImageName = (_imageName == "ellipses_vertical.png") 
                                    ? "ellipses_horizontal.png" 
                                    : "ellipses_vertical.png";
        });
    }

    int _count;
    public int Count
    {
        get { return _count; }
        set { if (_count != value) { _count = value; OnPropertyChanged("Count"); } }
    }

    string _imageName;
    public string ImageName
    {
        get { return _imageName; }
        set { if (_imageName != value) { _imageName = value; OnPropertyChanged("ImageName"); } }
    }

    public ICommand UpCount { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

我认为用简单的图像代替按钮会更好。但是,Image 没有原生的“点击”处理或 ICommand 处理。使用TapGestureRecognizer,您可以将此类行为附加到其他元素,包括图像。代码看起来像这样......

var tg= new TapGestureRecognizer();
tg.Tapped += (s, e) => {
    // handle the tap
};
image.GestureRecognizers.Add(tg);

每个 ViewCell 都有一个此手势识别器需要为其附加的图像。但是,我无法在模型中按名称引用图像。

有没有办法为每个 ViewCell 的图像启用点击处理程序并处理模型中的点击(不是代码隐藏)?

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    是的,您可以在 Xaml 中添加 TapGestureRecognizer 并在 Viewmodel 中接收命令。如需更多信息,请查看Xamarin Documentation

    在你的情况下,它看起来像这样。

    <Image Source="{Binding ImageName}">
        <Image.GestureRecognizers>
            <TapGestureRecognizer
                Command="{Binding UpCount}" />
        </Image.GestureRecognizers>
    </Image>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多