在 OnNavigatedTo() 中填充 ObservableCollection<MyClass> 时 UWP 应用程序崩溃

如何解决在 OnNavigatedTo() 中填充 ObservableCollection<MyClass> 时 UWP 应用程序崩溃

我认为这是一次非常奇怪的崩溃。

选择 FirstPage 时,UWP 应用“有时”会失败。此页面有一个 AdaptativeGridView,其中每个项目都是一个 FlipView。所有 FlipView 的 ItemsSource 都是相同的,代码隐藏中唯一的 ObservableCollection。

UI 捕获示例:ui-example

当您在 ObservableCollection 中加载数据时,问题发生在 UWP 应用程序中,在 OnNavigatedTo() 方法的异步版本中。

如果您使用完全同步的 OnNavigatedTo() 来加载 ObservableCollection,到目前为止我还没有看到这个问题。

输出错误为:

'Proj.UWP.Blank.NavigationTest.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'C:\Program Files\WindowsApps\Microsoft.NET.CoreFramework.Debug.2.2_2.2.29301.2_x86__8wekyb3d8bbwe\System.Diagnostics.Debug.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
The thread 0x39c has exited with code 0 (0x0).
The thread 0x3284 has exited with code 0 (0x0).
'Proj.UWP.Blank.NavigationTest.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'C:\Program Files\WindowsApps\Microsoft.NET.CoreFramework.Debug.2.2_2.2.29301.2_x86__8wekyb3d8bbwe\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Proj.UWP.Blank.NavigationTest.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'C:\Program Files\WindowsApps\Microsoft.NET.CoreFramework.Debug.2.2_2.2.29301.2_x86__8wekyb3d8bbwe\System.Collections.Concurrent.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Proj.UWP.Blank.NavigationTest.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'C:\Program Files\WindowsApps\Microsoft.NET.CoreFramework.Debug.2.2_2.2.29301.2_x86__8wekyb3d8bbwe\System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Exception thrown: 'System.Exception' in System.ObjectModel.dll
An exception of type 'System.Exception' occurred in System.ObjectModel.dll but was not handled in user code
The operation attempted to access data outside the valid range (Exception from HRESULT: 0x8000000B)

'Proj.UWP.Blank.NavigationTest.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\PrivateAssemblies\Runtime\Microsoft.VisualStudio.Debugger.Runtime.NetCoreApp.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'Proj.UWP.Blank.NavigationTest.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'C:\Program Files\WindowsApps\Microsoft.NET

堆栈跟踪是:

   at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender,NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index,T item)
   at System.Collections.ObjectModel.Collection`1.Add(T item)
   at Proj.UWP.Blank.NavigationTest.Pages.FirstPage.FillFlipViewData(List`1 filenames) in C:\Users\**\source\repos\Sol.UWP.Blank.NavigationTest\Proj.UWP.Blank.NavigationTest\Pages\FirstPage.xaml.cs:line 71
   at Proj.UWP.Blank.NavigationTest.Pages.FirstPage.<OnNavigatedTo>d__9.MoveNext() in C:\Users\**\source\repos\Sol.UWP.Blank.NavigationTest\Proj.UWP.Blank.NavigationTest\Pages\FirstPage.xaml.cs:line 61

代码隐藏是:

    public sealed partial class FirstPage : Page
    {

        public ObservableCollection<MyAdaptativeGridViewItem> AdaptativeGridViewData { get; set; } = new ObservableCollection<MyAdaptativeGridViewItem>()
        {
            new MyAdaptativeGridViewItem(1,"Item 1"),new MyAdaptativeGridViewItem(2,"Item 2"),new MyAdaptativeGridViewItem(3,"Item 3"),new MyAdaptativeGridViewItem(4,"Item 4"),};

        public ObservableCollection<MyFlipViewItem> FlipViewData { get; set; } = new ObservableCollection<MyFlipViewItem>();

        public FirstPage()
        {
            // Note that every time we navigate to this Page
            // the full class is instantiated from scratch
            // Hence,the constructor is always executed
            // and all properties are initialized
            this.InitializeComponent();
        }

        #region Async version
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // Get in a List<string> all image locations
            var filenames = await LoadDataAsync();

            // This function generates the FlipViewData ObservableCollection
            // that is binded to the UI
            FillFlipViewData(filenames);
        }

        private void FillFlipViewData(List<string> filenames)
        {
            // Note that each time .Add() is used in a ObservableCollection
            // the UI "is notified" of the change
            for (int i = 0; i < filenames.Count; i++)
            {
                var name = filenames[i];
                FlipViewData.Add(new MyFlipViewItem(i,"/Assets/Images/" + name));
            }
        }

        public async Task<List<string>> LoadDataAsync()
        {
            List<string> result = new List<string>();
            string absPath = Windows.ApplicationModel.Package.Current.InstalledLocation.Path
                + "\\Assets\\Images";
            var storageFolder = await StorageFolder.GetFolderFromPathAsync(absPath);
            var files = await storageFolder.GetFilesAsync();
            foreach (var f in files)
                result.Add(f.Name);

            return result;
        }
        #endregion

    }

用户界面是:

    <Page.Resources>

        <Thickness x:Key="MediumLeftRightMargin">24,24,0</Thickness>
        <Thickness x:Key="XSmallLeftTopRightBottomMargin">8,8,8</Thickness>
        <Thickness x:Key="XXSmallTopMargin">0,4,0</Thickness>

        <x:Double x:Key="MediumFontSize">16</x:Double>

        <Style x:Key="BodyTextStyle" TargetType="TextBlock">
            <Setter Property="FontWeight" Value="Normal" />
            <Setter Property="FontSize" Value="{StaticResource MediumFontSize}" />
            <Setter Property="TextTrimming" Value="CharacterEllipsis" />
            <Setter Property="TextWrapping" Value="Wrap" />
        </Style>

        <DataTemplate x:Name="FlipView_ItemTemplate" x:DataType="models:MyFlipViewItem">
            <Grid>
                <Image Source="{x:Bind ImageLocation,Mode=OneWay}" Stretch="Uniform" HorizontalAlignment="Center" Width="100"/>
            </Grid>
        </DataTemplate>

        <DataTemplate x:Key="AdaptativeGridView_ItemTemplate" x:DataType="models:MyAdaptativeGridViewItem">
            <Grid x:Name="itemThumbnail"
                  Padding="{StaticResource XSmallLeftTopRightBottomMargin}"
                  Background="{ThemeResource SystemControlPageBackgroundChromeLowBrush}">

                <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">

                    <FlipView Width="150" Height="150"
                          ItemTemplate="{StaticResource FlipView_ItemTemplate}"
                          ItemsSource="{Binding ElementName=ThisPrincipalPage,Path=FlipViewData,Mode=OneWay}"/>

                    <TextBlock
                                Margin="{StaticResource XXSmallTopMargin}"
                                HorizontalAlignment="Center"
                                Style="{ThemeResource BodyTextStyle}"
                                Text="{x:Bind PresetName,Mode=OneWay}" />
                </StackPanel>
            </Grid>
        </DataTemplate>


    </Page.Resources>


    <Grid x:Name="ContentArea" Margin="{StaticResource MediumLeftRightMargin}">
        <Grid
            Background="{ThemeResource SystemControlPageBackgroundChromeLowBrush}">
            <!--
                The SystemControlPageBackgroundChromeLowBrush background represents where you should place your content. 
                Place your content here.
            -->
            <StackPanel>

                <GridView
                Padding="{StaticResource MediumLeftRightMargin}"
                IsItemClickEnabled="True"
                ItemTemplate="{StaticResource AdaptativeGridView_ItemTemplate}"
                ItemsSource="{x:Bind AdaptativeGridViewData,Mode=OneWay}"
                SelectionMode="None"/>

            </StackPanel>
        </Grid>
    </Grid>

随意找到代码 here 并进行测试。

额外观察:

  • 在 github 项目中,您将拥有一个完全同步的版本(只需注释/取消注释区域即可测试)。

  • 在同步版本中,代码永远不会失败,添加项目时的 UI 状态(就在 FlipViewData.Add() 之前)看起来总是像空白内容。

UI-unloaded-in-aync-and-sync

但是,在异步版本中,UI 有时是空白的,有时是部分加载的,例如:

UI-partially-loaded-in-async

我注意到只有在此 UI 状态下添加项目时才会出现此问题。

  • 将第一项添加到 FlipViewData 后总是会发生错误。

Visual-Studio-capture

最后:

也许,当 ObservableColletion 尝试在 FlipViewData.Add() 之后通知更改时,这表明了一些不一致的数据(集合具有“不同”数量的项目,具体取决于谁看起来像是线程问题)。但是,添加是在 UI 线程中进行的。

替代方案

有多种替代方法可以制作相同的 UI,而不会出现所描述的问题。这不是我想要找到的。但是,其中一种方法可能会为所描述的问题提供一些额外的线索。具体来说,在所描述的方法中,GridView 绑定到一个 ObservableCollection,并且每个 GridView 项本身都绑定到另一个 ObservableCollection。两个 ObservableCollections 在代码隐藏中都是两个不同的属性。

如果数据模型被重新定义为包含在代码隐藏中的单个属性中,即嵌套的 ObservableCollection,即

,则所描述的错误似乎不会发生

新的数据模型

    public class MyGridViewItem
    {
        public int PresetIndex { get; set; }
        public string PresetName { get; set; }
        public ObservableCollection<MyFlipViewItem> FlipViewData { get; set; }
    }

和代码隐藏中的单个属性

public ObservableCollection<MyGridViewItem> GridViewData { get; set; } = new ObservableCollection<MyGridViewItem>();

使用这种方法,并在 XAML 文件中的所有绑定中使用 x:Bind(不再需要经典绑定),问题似乎没有出现。

因此,似乎嵌套的 ObservableCollection 工作正常,但使用两个单独的 ObservableCollection(一个用于根 UI GridView 元素,另一个用于子 UI FlipView 元素)不是。可能这和官方的注释有关documentation

ObservableCollection 必须是根元素,因为 x:TypeArguments 必须用于指定受约束的属性 通用 ObservableCollection 的类型仅在 根元素的对象元素。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res