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

切换MAUI应用Shell后摄像头无法激活问题求助

解决MAUI中ZXing CameraBarcodeReaderView返回后再次进入不显示画面的问题

问题根源

Shell的ShellContent默认会缓存页面实例,第二次进入CameraPage时不会重新执行构造函数,而ZXing的CameraBarcodeReaderView未自动重启摄像头捕获,导致画面无法显示。

解决方案

方案1:通过页面生命周期事件控制扫描状态(推荐)

在CameraPage.xaml.cs中重写OnAppearing和OnDisappearing方法,在页面显示时启动扫描,隐藏时停止并释放资源:

protected override void OnAppearing()
{
    base.OnAppearing();
    // 确保扫描开启,触发摄像头重新捕获
    cameraBarcodeReaderView.IsScanning = true;
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    // 停止扫描,释放摄像头资源
    cameraBarcodeReaderView.IsScanning = false;
}

如果上述方法无效,可尝试在OnAppearing中额外重置摄像头位置(部分平台需要):

protected override void OnAppearing()
{
    base.OnAppearing();
    cameraBarcodeReaderView.CameraLocation = CameraLocation.Rear; // 切换摄像头位置触发重新绑定
    cameraBarcodeReaderView.IsScanning = true;
}

方案2:禁用CameraPage的缓存

修改AppShell.xaml中CameraPage对应的ShellContent,直接实例化页面而非使用DataTemplate,这样每次导航都会创建新页面实例:

<!-- 替换原CameraPage的ShellContent -->
<ShellContent
    Title="Camera"
    Content="{local:CameraPage}"
    Route="CameraPage" />

注意:此方法会每次创建新页面,可能增加内存开销,适合页面逻辑简单的场景。

方案3:手动管理页面实例

在主页面跳转时,移除已缓存的CameraPage实例并创建新实例:

async private void OnCameraClicked(object sender, EventArgs e)
{
    // 移除已存在的CameraPage实例
    var existingItem = Shell.Current.Items.FirstOrDefault(i => i.Route == "CameraPage");
    if (existingItem != null)
    {
        Shell.Current.Items.Remove(existingItem);
    }
    // 添加新的CameraPage实例
    Shell.Current.Items.Add(new ShellContent
    {
        Title = "Camera",
        Content = new CameraPage(),
        Route = "CameraPage"
    });
    // 导航到新页面
    await Shell.Current.GoToAsync("//CameraPage");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:43:25