CarouselView是否有类似listview的关于所选项目的事件处理程序


<ContentPage.ToolbarItems>
<ToolbarItem Clicked="ToolbarItem_Clicked"
Text="+ Search "
>
</ToolbarItem>
</ContentPage.ToolbarItems>
<StackLayout>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
</Grid>


<StackLayout Grid.Row="0" >
<CarouselView x:Name="carouselview" 
PeekAreaInsets="50"
>
<CarouselView.ItemsLayout>
<LinearItemsLayout Orientation="Horizontal"
ItemSpacing="20"
/>
</CarouselView.ItemsLayout>
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame HasShadow="True"
BorderColor="DarkGray"
CornerRadius="5"
Margin="20"
HeightRequest="500"
WidthRequest="500"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand">
<StackLayout>
<Label Text="{Binding NameProduct}"
FontAttributes="Bold"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="Center" />
<Image Source="xamarinremovebg.png"
Aspect="AspectFill"
HeightRequest="150"
WidthRequest="150"
HorizontalOptions="Center" />

</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
</StackLayout>
</StackLayout>

这是我的代码,我想在CarouselView中使用itemselected事件。我指的是在listview中选择的项目。但是在CarouselView中没有。我只想当我点击CarouselView中的项目1时,我想转到项目1的详细页面。非常感谢您的帮助。

没有像ListView中那样的默认事件。但是,我们可以在DataTemplate上添加TapGestureRecognizer作为解决方法。

在xaml中

1.设置ContentPage 的名称

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="xxx.MainPage"
x:Name="page"  
>
  1. 添加TapGestureRecognizer
<DataTemplate>
<StackLayout>

<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ItemSelectedCommand,Source={x:Reference page}}" CommandParameter="{Binding .}"/>
</StackLayout.GestureRecognizers> 

<Frame>
//...
</Frame>
</StackLayout>
</DataTemplate>

在ViewModel中

public ICommand ItemSelectedCommand{ get; set; }

在构造函数中:

ItemSelectedCommand= new Command((item)=>{
// item here is type of the model in the ItemSource of CarouselView
// var model = item as yourmodel

});

最新更新