我会保持简洁。我有一个实现 ItemTemplate 的 ListBox。DataTemplate 包含一个复选框。我加载了大约 2000 个项目。我检查前 5 个项目,滚动到底部并选择最后 5 个项目。然后我向上滚动到顶部项目,并注意到我的前 5 个检查项目已被修改。
<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));
}
}
}
希望对此有一个很好的解释 - 这是一个 MS 错误。这发生在 .NET 3.5 和 4.0 中。当 VirtualingStackPanel.IsVirtualizing 设置为 false 时,不会发生这种行为,但在现实世界中,没有虚拟化的加载是痛苦的。
一些见解会很好。
提前致谢,
安德烈斯·奥利瓦雷斯