当我使用
ItemsSource
作为 List<ApplicationModel.Package>
对象填充 ListView(或 ItemsView)时,加载控件时有时会发生崩溃。
如果我有一个使用 Package.Logo 作为源的
Image
,崩溃的几率会增加很多。
当我触发控件时,我希望它显示所有已安装的应用程序、它们的图标等。它成功地做到了,直到我尝试滚动......这就是我遇到崩溃的时候。
使用此代码:
<ContentDialog
x:Class="Program.AllAppsList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TITLE"
Style="{ThemeResource DefaultContentDialogStyle}">
<Grid>
<ListView ItemsSource="{x:Bind Packages}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!-- High crash chance with this uncommented -->
<Image Width="64" Height="64" Margin="5">
<Image.Source>
<BitmapImage UriSource="{Binding Logo, TargetNullValue='ms-appx:///Assets/fallback.png', FallbackValue='ms-appx:///Assets/fallback.png'}" />
</Image.Source>
</Image>
<StackPanel Orientation="Vertical" Margin="5">
<TextBlock Text="{Binding DisplayName, TargetNullValue='Unknown', FallbackValue='Unknown'}" FontWeight="Bold" />
<TextBlock Text="{Binding PublisherDisplayName, TargetNullValue='Unknown', FallbackValue='Unknown'}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ContentDialog>
using Microsoft.UI.Xaml.Controls;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using Windows.ApplicationModel;
using Windows.Management.Deployment;
namespace Program
{
public sealed partial class AllAppsList : ContentDialog
{
public List<Package> Packages { get; set; } = new List<Package>();
public AllAppsList()
{
Packages = GetAllInstalledPackages();
this.DataContext = this;
this.InitializeComponent();
}
public static List<Package> GetAllInstalledPackages()
{
var pm = new PackageManager();
return pm.FindPackagesForUser(WindowsIdentity.GetCurrent().User?.Value).ToList();
}
private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
}
private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
}
}
}
尝试以下操作:
public AllAppsList()
{
var packages = GetAllInstalledPackages();
// Magic block of code. Not sure why it works.
var list = new List<string>();
foreach (var package in packages)
{
list.Add(package.DisplayName);
}
Packages = packages;
this.DataContext = this;
this.InitializeComponent();
}
另外,由于似乎某些软件包,特别是在 DevelopmentMode 中安装的软件包没有正确的安装位置,请先尝试过滤它们:
public static List<Package> GetAllInstalledPackages()
{
var pm = new PackageManager();
return pm.FindPackagesForUser(WindowsIdentity.GetCurrent().User?.Value)
.Where(package => package.IsDevelopmentMode is false)
.ToList();
}