WPFアプリケーションで大量のデータを処理する必要があります。
大きなコレクションをListViewItemContainerStyle
にバインドし、を使用してリストアイテムのIsSelectedプロパティをオブジェクトのIsSelected
プロパティにバインドしているため、アイテムがで選択されるListView
と、オブジェクトのIsSelected
プロパティもtrueに設定されます。これを行うことで、リストで選択されたオブジェクトのみに対してコマンドを簡単に実行できます。
ListViewでUI仮想化を使用しているのは、そうしないとアプリが遅くなるためです。ただし、コレクション全体のサブセットのみがリストに表示されるため、CTRL + Aを使用してリスト内のすべてのアイテムを選択すると、ロードされたアイテムのみのIsSelected
プロパティがtrueに設定されます。表示されていないアイテム(仮想化されているアイテム)のIsSelected
プロパティはfalseに設定されています。これは問題です。リスト内のすべてのアイテムを選択するとIsSelected
、コレクション内のすべてのアイテムに対してプロパティがtrueに設定されていると予想されるためです。
問題を説明するために、いくつかのサンプルコードを作成しました。
MainWindow.xaml
<Window x:Class="VirtualizationHelp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" x:Name="wnd">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="Click me" Click="Button_Click" />
<ListView Grid.Row="1" ItemsSource="{Binding Path=Persons, ElementName=wnd}">
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
</Grid>
</Window>
MainWindow.xaml.cs
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace VirtualizationHelp
{
public partial class MainWindow : Window
{
List<SelectablePerson> _persons = new List<SelectablePerson>(10000);
public List<SelectablePerson> Persons { get { return _persons; } }
public MainWindow()
{
for (int i = 0; i < 10000; i++)
{
SelectablePerson p = new SelectablePerson() { Name = "Person " + i, IsSelected = false };
_persons.Add(p);
}
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
int count = Persons.Where(p => p.IsSelected == true).Count();
(sender as Button).Content = count.ToString();
}
}
public class SelectablePerson
{
public string Name { get; set; }
public bool IsSelected { get; set; }
public override string ToString()
{
return Name;
}
}
}
フォームの上部にあるボタンをクリックすると、「IsSelected」プロパティがtrueに設定されているコレクション内のアイテムがカウントされます。CTRL+Aを押してリスト内のすべてのアイテムを選択すると、19個のアイテムのみが選択されていることがわかります。
誰かがこの問題を回避する方法を知っていますか?パフォーマンスがひどいので、仮想化をオフにできません。