我有以下概念证明:
XAML 窗口:
<Window x:Class="WpfApplication1.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">
<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" />
<DataGridTemplateColumn >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Mode=TwoWay, Path=Enabled}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Window>
后面的代码:
using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public ObservableCollection<Data> Items { get; private set; }
public MainWindow()
{
InitializeComponent();
this.Items = new ObservableCollection<Data>();
this.DataContext = this;
for (int index = 0; index < 30; index++)
{
this.Items.Add(new Data() {Enabled = true });
}
}
}
public class Data
{
public bool Enabled { get; set; }
}
}
执行应用程序,取消选中顶部的一些框,向下滚动,再次更改一些框并向上滚动。瞧,复选框再次被选中!
我是否遗漏了什么,或者我应该向 Microsoft 填写一个错误?
编辑:感谢您的回复,但它与 INotify 或复选框无关,TextBox 和 INotify 也会发生同样的情况。滚动后您不需要单击复选框,只需取消选中一些,向下滚动,向上滚动并瞧,它们会再次被选中。检查此代码:
<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTemplateColumn >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Mode=TwoWay, Path=Enabled}" />
<TextBox Text="{Binding Text}" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Window>
以及背后的代码:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public ObservableCollection<Data> Items { get; private set; }
public MainWindow()
{
InitializeComponent();
this.Items = new ObservableCollection<Data>();
this.DataContext = this;
for (int index = 0; index < 30; index++)
{
this.Items.Add(new Data() { Enabled = true, Text = index.ToString() });
}
}
}
public class Data : INotifyPropertyChanged
{
private bool _enabled;
public bool Enabled
{
get { return _enabled; }
set
{
if (value != _enabled)
{
_enabled = value;
this.OnPropertyChanged("Enabled");
}
}
}
private string _text;
public string Text
{
get { return _text; }
set
{
if (value != _text)
{
_text = value;
this.OnPropertyChanged("Text");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string name)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
#endregion
}
}