I'll keep it concise. I have a ListBox that implements an ItemTemplate. The DataTemplate contains a checkbox. I load about 2000 items. I check the first 5 items, scroll to the bottom and select the last 5 items. I then scroll up to the top item and noticed that my first 5 check items have been modified.
<Window
x:Class="CheckItems.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CheckItems"
Title="Window1" Height="300" Width="300"
>
<DockPanel>
<StackPanel DockPanel.Dock="Bottom" >
<Button Content="Test" Click="Button_Click"/>
</StackPanel>
<ListBox DockPanel.Dock="Left"
x:Name="users"
ItemsSource="{Binding Path=Users}"
>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox>
<TextBlock Text="{Binding Path=Name}"/>
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
</Window>
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
namespace CheckItems
{
public partial class Window1 : Window
{
ViewModel controller;
public Window1()
{
DataContext = controller = new ViewModel();
InitializeComponent();
controller.Users = LoadData();
}
private List<User> LoadData()
{
var newList = new List<User>();
for (var i = 0; i < 2000; ++i)
newList.Add(new User { Name = "Name" + i, Age = 100 + i });
return newList;
}
private void Button_Click(object sender, RoutedEventArgs e)
{ }
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
public class ViewModel : INotifyPropertyChanged
{
private List<User> users;
public event PropertyChangedEventHandler PropertyChanged;
public List<User> Users
{
get { return users; }
set { users = value; NotifyChange("Users"); }
}
protected void NotifyChange(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Hopefully there is a good explanation for this besides - it's a MS bug. This occurs in .NET 3.5 and 4.0. When VirtualingStackPanel.IsVirtualizing is set to false, this behavior does not occur, but in a real world situo, loading without virtualization is painful.
Some insight would be nice.
Thanks in advance,
Andres Olivares