如何解决在 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 有时是空白的,有时是部分加载的,例如:
我注意到只有在此 UI 状态下添加项目时才会出现此问题。
- 将第一项添加到 FlipViewData 后总是会发生错误。
最后:
也许,当 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 举报,一经查实,本站将立刻删除。