我是Xamarin.Forms的初学者。请帮助:
我有一个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>
点击后,我需要更改Image.Source。但是在CodeBehind中,我需要选择ListView对象。
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;
}
如何从XAML将PostViewModel发布到我的方法? 当用户点击时,我需要更改该图像。但是在代码中,我需要listView Item对象来更改其属性。
答案 0 :(得分:0)
发件人的BindingContext
应该包含您需要的数据
private void AddLike(object sender, EventArgs args)
{
var post = (PostViewModel) ((Image)sender).BindingContext;
if (post == null)
return;
post.IsLiked = true;
SelectedPost = null;
}