我有一个CarouselView,它绑定到图像的ItemsSource。
但是我想通过更改CarouselView的索引来更改当前显示的图像。
我尝试使用CarouselView.Position来选择元素的索引。但不幸的是,这不起作用。
我该如何实现?
谢谢
最佳答案
我尝试使用CarouselView.Position来选择元素的索引。但不幸的是,这不起作用。
由于您要对ItemsSource
的CarouselView
使用数据绑定,因此可以为图像模型实现INotifyPropertyChanged
接口。
例如:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:cv="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
x:Class="FormsIssue2.Page1">
<Grid>
<cv:CarouselView ItemsSource="{Binding Zoos, Mode=OneWay}" x:Name="CarouselZoos">
<cv:CarouselView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image Grid.RowSpan="2" Aspect="AspectFill" Source="{Binding ImageUrl, Mode=OneWay}" />
<StackLayout Grid.Row="1" BackgroundColor="#80000000" Padding="12">
<Label TextColor="White" Text="{Binding Name, Mode=OneWay}" FontSize="16" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
</StackLayout>
</Grid>
</DataTemplate>
</cv:CarouselView.ItemTemplate>
</cv:CarouselView>
</Grid>
</ContentPage>
后面的代码:
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
Zoos = new ObservableCollection<Zoo>
{
new Zoo
{
ImageUrl = "http://wallpaper-gallery.net/images/image/image-13.jpg",
Name = "Woodland Park Zoo"
},
new Zoo
{
ImageUrl = "https://s3-us-west-1.amazonaws.com/powr/defaults/image-slider2.jpg",
Name = "Cleveland Zoo"
},
new Zoo
{
ImageUrl = "http://i.stack.imgur.com/WCveg.jpg",
Name = "Phoenix Zoo"
}
};
//CarouselZoos.ItemsSource = Zoos;
this.BindingContext = this;
CarouselZoos.ItemSelected += CarouselZoos_ItemSelected;
}
private void CarouselZoos_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as Zoo;
if (item == null)
return;
item.ImageUrl = "https://3.bp.blogspot.com/-W__wiaHUjwI/Vt3Grd8df0I/AAAAAAAAA78/7xqUNj8ujtY/s1600/image02.png";
}
public ObservableCollection<Zoo> Zoos { get; set; }
}
public class Zoo : INotifyPropertyChanged
{
private string _ImageUrl;
public string ImageUrl
{
get { return _ImageUrl; }
set
{
if (value != _ImageUrl)
{
_ImageUrl = value;
OnPropertyChanged("ImageUrl");
}
}
}
private string _Name;
public string Name
{
get { return _Name; }
set
{
if (value != _Name)
{
_Name = value;
OnPropertyChanged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
选择一个项目后,您可以在
SelectedItemChangedEventArgs
中找到该项目的实例,然后可以更改该项目的图像源。更新:
根据我们的讨论,我认为缩略图的
CarouselView
和较大图像的CarouselView
的项目来源按相同的顺序排列,然后在缩略图中选择该项目时,您可以获取缩略图的位置并滚动CarouselView
对于像这样的大图像:var postion = CarouselThunbnails.Position;
CarouselImages.Position = postion;