从视单元内的图像访问来自手势的列表数据

时间:2018-07-25 16:40:54

标签: c# listview xamarin xamarin.forms

我在ViewCell内有一个图像,我向该图像添加了一个TapGestureRecognizer,现在当用户单击该图像时,我要访问数据ViewCell中的数据< / p>

我该怎么做?

2 个答案:

答案 0 :(得分:2)

这是在ViewCell上传递数据的简单代码。

代码UI-

<ListView ItemsSource="{Binding ListItem}" x:Name="lst">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
              <StackLayout>
               <Image Source="abcd" Aspect="AspectFit">
               <Image.GestureRecognizers>
               <TapGestureRecognizer Command="{Binding ClickCommand}" 
                      Source={x:Reference lst}}" 
                      CommandParameter="{Binding .}" />
                 </Image.GestureRecognizers>
                 </Image>
               </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

代码ViewModel-

 Public Class MainViewModel
{
   Command clickCommand;
    public Command ClickCommand
    {
        get
        {
       return clickCommand ?? (menuTapCommand = new Command<Object>(GetImage));
        }
    }
Private Void GetImage(Object obj)
{
 //Todo
}}

答案 1 :(得分:0)

为XF ViewCell创建DataTemplate时,该图像的BindingContext和单元格本身就是 Data 对象。我有一个带有图像和TapGestureRecognizer的 ViewCell 。它会在我拥有所需数据的 Data 对象中正确执行ICommand。您将需要在数据对象中将ICommand分配给ListView。

<ListView ItemsSource="{Binding ListItem}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    <Image Source="abcd">
                        <Image.GestureRecognizers>
                            <TapGestureRecognizer Command="{Binding ClickCommand}" />
                        </Image.GestureRecognizers>
                    </Image>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ListView的 Data 对象应具有ICommand

public class MyDataObject
{
    private Action<string> _openUrl;
    private string _url;

    public MyDataObject(string url, Action<string> openUrl)
    {
        _url = url;
        _openUrl = openUrl;

        ClickCommand = new Command(AccessOtherData);
    }

    public ICommand ClickCommand { get; }

    // Other data properties and such

    private void AccessOtherData()
    {
        // Call method to open _url
        _openUrl(_url);
    }
}

您的页面ObservableCollection中的ViewModel应该具有数据对象的列表

ViewModel:

public class ViewModel
{
    public event EventHandler<string> OpenUrl;

    // List filled with the MyDataObject
    public ObservableCollection<MyDataObject> Collection { get; set; }

    private void FillCollection()
    {
        // Create all MyDataObjects here
        // Each object will be created like this
        Collection.Add(new MyDataObject("insert url here", OpenUrlFromObject));
    }

    private void OpenUrlFromObject(string url)
    {
        OpenUrl?.Invoke(this, url); // Subscribe to this event in your Page and open
    }
}