Reputation: 427
I have a image inside a ViewCell
, I've added a TapGestureRecognizer
to the image, now when the user clicks the image I want to Access the data from data ViewCell
How can I do that?
Upvotes: 0
Views: 225
Reputation: 687
When creating a DataTemplate
for a XF ViewCell, the BindingContext
of that image and the cell itself is the Data object. I have a ViewCell with an image and a TapGestureRecognizer. It properly executes the ICommand
in my Data object where I have the data needed. You will need an ICommand
in your data object given to the 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>
The Data object for your ListView should have the 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);
}
}
Your ObservableCollection
in your pages ViewModel should have a list of Data objects
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
}
}
Upvotes: 0
Reputation: 673
This is simple code to passing data click on ViewCell.
Code 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>
Code ViewModel--
Public Class MainViewModel
{
Command clickCommand;
public Command ClickCommand
{
get
{
return clickCommand ?? (menuTapCommand = new Command<Object>(GetImage));
}
}
Private Void GetImage(Object obj)
{
//Todo
}}
Upvotes: 2