Reputation: 113
I'm beginner in Xamarin.Forms. Please help:
I have a listView:
<ListView Grid.Row="2" ItemsSource="{Binding PostsVm.Posts}" HasUnevenRows="True"
SelectedItem="{Binding PostsVm.SelectedPost, Mode=TwoWay}"
ItemSelected="DisableSelection">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand" Grid.Row="2" Margin="10,0,10,0">
<Image Source="{Binding Like}" WidthRequest="30">
<Image.GestureRecognizers>
<TapGestureRecognizer
Tapped="AddLike"
NumberOfTapsRequired="1" />
</Image.GestureRecognizers>
</Image>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
After tapping I need to change Image.Source. But in CodeBehind I need ListView selected object.
PostViewModel:
private bool _isLiked;
public bool IsLiked
{
get { return _isLiked; }
set
{
SetValue(ref _isLiked, value);
OnPropertyChanged(Like);
}
}
public string Like
{
get { return IsLiked ? "likered.png" : "like.png"; }
}
PostsViewModel:
public ObservableCollection<PostViewModel> Posts { get; private set; }
public ICommand AddLikeCommand { get; private set; }
private PostViewModel _selectedPost;
public PostViewModel SelectedPost
{
get { return _selectedPost; }
set { SetValue(ref _selectedPost, value); }
}
public PostsViewModel()
{
Posts = new ObservableCollection<PostViewModel>();
Image = "http://lorempixel.com/output/sports-q-c-640-480-9.jpg",
});
AddLikeCommand = new Command<PostViewModel>(vm => AddLike(vm));
}
private void SelectPost(PostViewModel post)
{
if (post == null)
return;
SelectedPost = null;
}
private void AddLike(PostViewModel post)
{
if (post == null)
return;
post.IsLiked = true;
SelectedPost = null;
}
How I can get PostViewModel post to my method from XAML ? When user tapped on like I need change that image. But in code i need listView Item object to change it property.
Upvotes: 0
Views: 66
Reputation: 89102
the sender's BindingContext
should contain the data you need
private void AddLike(object sender, EventArgs args)
{
var post = (PostViewModel) ((Image)sender).BindingContext;
if (post == null)
return;
post.IsLiked = true;
SelectedPost = null;
}
Upvotes: 0