我正在尝试在图像中绑定TapGestureRecognizer(如here所示),但ViewModel中的相对Icommand不会被触发。我正在使用lightMVVM框架。
这是我的代码:
<?xml version="1.0" encoding="utf-8" ?>
<CarouselPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ZoccoloManager.Views.DetailsPage"
ItemsSource="{Binding Cows}">
<CarouselPage.ItemTemplate>
<DataTemplate>
<ContentPage x:Name="DetailsPage">
<RelativeLayout>
<Image x:Name="fl_left"
Source="zoccolo_leftside.png"
RelativeLayout.WidthConstraint=
"{ConstraintExpression Type=RelativeToParent,
Property=Width,
Factor=0.3 }"
RelativeLayout.HeightConstraint=
"{ConstraintExpression Type=RelativeToParent,
Property=Height,
Factor=0.3 }"
RelativeLayout.XConstraint =
"{ConstraintExpression Type=RelativeToParent,
Property=Width,
Factor=0.07}"
RelativeLayout.YConstraint =
"{ConstraintExpression Type=RelativeToParent,
Property=Height,
Factor=0.07}">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding Path=BindingContext.TapImageCommand, Source={x:Reference DetailsPage}}" />
</Image.GestureRecognizers>
</Image>
</RelativeLayout>
</ContentPage>
</DataTemplate>
</CarouselPage.ItemTemplate>
</CarouselPage>
并在ViewModel中:
public class DetailsViewModel : ViewModelBase
{
private readonly INavigationService _navigationService;
private IRepository _repository;
public ICommand TapImageCommand { get; private set; }
public ObservableCollection<Cow> Cows { get; set; }
public DetailsViewModel(INavigationService navigationService)
{
_repository = ServiceLocator.Current.GetInstance<IRepository>();
Debug.WriteLine(DateTime.Now + ": Calling LoadCows");
LoadCows();
Debug.WriteLine(DateTime.Now + ": Called LoadCows");
_navigationService = navigationService;
TapImageCommand = new Command(OpenPopup);
}
private async Task LoadCows()
{
Debug.WriteLine(DateTime.Now + ": Started execution LoadCows");
await Task.Run(() =>
{
Cows = new ObservableCollection<Cow>();
foreach (var cow in _repository.GetCompany(0).Cows)
{
Cows.Add(cow);
}
});
Debug.WriteLine(DateTime.Now + ": Finished execution LoadCows");
}
private void OpenPopup()
{
Debug.WriteLine("Opening popup ");
}
}
一切都很好,但调试它的ICommand TapImageCommand的getter永远不会被调用。对ObservableCollection的绑定工作正常,我有正确的页数作为列表中的元素。
我错过了什么?
答案 0 :(得分:1)
好的,我已经弄明白问题是什么了。
Source={x:Reference DetailsPage}
与xml命名空间定义上的类名冲突。
在主Tag CarouselPage中添加适当的x:Name
并在引用中使用相同的名称,使其工作正常。