You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# Xamarin Forms Android中获取CarouselView当前图片源

如何点击按钮移除CarouselView的当前显示图片

问题场景

需要实现点击ImageButton时,删除CarouselView中当前正在显示的图片,但不知道如何获取当前活跃的图片项,现有代码如下:

Page.xaml 代码

<StackLayout Padding="5">
    <CarouselView x:Name="carousel" HeightRequest="600" IndicatorView="{x:Reference contImgs}">
        <CarouselView.ItemTemplate>
            <DataTemplate>
                <Image x:Name="activeImg" Source="{Binding Source}" Aspect="AspectFill"></Image>
            </DataTemplate>
        </CarouselView.ItemTemplate>
    </CarouselView>
    <IndicatorView x:Name="contImgs" IndicatorColor="#bbb" SelectedIndicatorColor="#000" IndicatorSize="12" IndicatorsShape="Circle"></IndicatorView>
    <ImageButton Source="drawable/icon_trash.png" WidthRequest="100" Clicked="btnDeleteImg" HeightRequest="100" AbsoluteLayout.LayoutBounds="0.98,0.07,50,50" AbsoluteLayout.LayoutFlags="PositionProportional"></ImageButton>
</StackLayout>

Page.xaml.cs 代码

private List<Image> imgsCarrousel = new List<Image>();

private void btnDeleteImg(object sender, EventArgs e)
{
    imgsCarrousel.Remove(imgSelected); // 想要实现类似这样的逻辑
}

解决方案

核心思路是操作数据源而非直接操作UI元素,利用CarouselView的CurrentItem属性获取当前显示项,配合ObservableCollection实现UI自动刷新:

  1. 定义图片数据模型
    先创建一个简单的模型类来存储图片路径,避免直接操作Image控件:

    public class ImageItem
    {
        public string Source { get; set; }
    }
    
  2. 替换数据源类型
    将原来的List<Image>换成ObservableCollection<ImageItem>,它会在集合变化时自动通知UI更新:

    private ObservableCollection<ImageItem> _imageItems;
    
    public YourPageName() // 替换成你的页面类名
    {
        InitializeComponent();
        // 初始化图片数据,替换成你的实际图片路径
        _imageItems = new ObservableCollection<ImageItem>
        {
            new ImageItem { Source = "drawable/img1.png" },
            new ImageItem { Source = "drawable/img2.png" },
            new ImageItem { Source = "drawable/img3.png" }
        };
        // 给CarouselView绑定数据源
        carousel.ItemsSource = _imageItems;
    }
    
  3. 实现删除逻辑
    在按钮点击事件中,通过CarouselView.CurrentItem获取当前显示的图片项,然后从数据源中移除:

    private void btnDeleteImg(object sender, EventArgs e)
    {
        // 判断当前项是否有效
        if (carousel.CurrentItem is ImageItem currentImage)
        {
            _imageItems.Remove(currentImage);
        }
    }
    

关键说明

  • ObservableCollection:相比List,它实现了INotifyCollectionChanged接口,删除/添加项时会自动触发UI刷新,无需手动更新CarouselView。
  • CarouselView.CurrentItem:这个属性直接指向当前正在显示的数据源项,不需要去查找或遍历UI控件,是官方推荐的获取当前活跃项的方式。

内容的提问来源于stack exchange,提问作者F205

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:25:20