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

MAUI实现滑动切换图片:滑动事件未触发问题求助

问题分析与修复

你的滑动事件无法触发主要有三个核心问题:

  • 事件绑定不匹配:XAML中绑定的是SwipeEnded事件,但后台实现的是SwipeView_SwipeChanging方法,名称不对应导致系统找不到处理逻辑。
  • 未指定允许的滑动方向:默认情况下SwipeView不会自动启用左右滑动,需要明确配置允许的方向。
  • 错误使用SwipeItemView:该控件用于定义滑动后显示的操作项(比如删除按钮),并非承载主内容的容器,直接将Image作为SwipeView的内容即可。

修复后的XAML代码

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Alm.MainPage">
    
    <!-- 配置允许左右滑动,绑定正确的SwipeChanging事件 -->
    <SwipeView SwipeChanging="SwipeView_SwipeChanging" 
               Threshold="200"
               AllowedSwipeDirections="Left,Right"
               SwipeMode="Both">
        <!-- 直接放置Image作为主内容,无需SwipeItemView -->
        <Image >
            <Image.Source>
                <UriImageSource x:Name="Sorsa" Uri="https://someurl.com/someimage.jpg"></UriImageSource>
            </Image.Source>
        </Image>
    </SwipeView>
 
</ContentPage>

后台代码(确保方法与事件绑定一致)

private void SwipeView_SwipeChanging(object sender, SwipeChangingEventArgs e) {
    // 滑动过程中触发,若想滑动结束后再切换,可改用SwipeEnded事件
    if (e.SwipeDirection == SwipeDirection.Left)
        Sorsa.Uri = HaeEdellinen();
    if (e.SwipeDirection == SwipeDirection.Right)
        Sorsa.Uri = HaeSeuraava();
}

// 需确保这两个方法能正确返回Uri对象
private Uri HaeEdellinen()
{
    // 实现返回上一张图片Uri的逻辑
    return new Uri("https://someurl.com/prev-image.jpg");
}

private Uri HaeSeuraava()
{
    // 实现返回下一张图片Uri的逻辑
    return new Uri("https://someurl.com/next-image.jpg");
}

额外说明

如果希望避免滑动过程中频繁切换图片,可将事件改为SwipeEnded,对应后台方法重命名为SwipeView_SwipeEnded,逻辑保持一致即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:50:27