我使用的是WPF DataGrid,并且我将单元格的IsSelected属性绑定到模型中的数据。如果在数据网格(VirtualizingStackPanel.IsVirtualizing="False"
)上关闭了虚拟化,则此操作效果良好。
然而,当我打开虚拟化,向下滚动时,我看到一些单元格不再被选中,尽管它们是在代码中被选中的。
我必须使用虚拟化,因为没有它,我的数据网格加载太慢了。有人对如何解决这个问题有什么建议吗?
更新:
我的代码(我绑定在b/c后面的代码中,直到运行时我才知道我需要多少列):
for (int i = 0; i < this.CurrentData.Data[0].Length; i++)
{
TheGrid.Columns.Add(
new DataGridTextColumn
{
Header = (this.CurrentData.Rank > 1) ? string.Format(this.culture, headerFormatString, i + 1) : string.Empty,
Binding = new Binding(string.Format("[{0}].DataValue", i)) { ValidatesOnDataErrors = true, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged },
Width = DataGridLength.Auto,
ElementStyle = new Style
{
TargetType = typeof(TextBlock),
Triggers = { this.errorTrigger }
},
EditingElementStyle = new Style
{
TargetType = typeof(TextBox),
Triggers = { this.errorTrigger }
},
CellStyle = new Style
{
TargetType = typeof(DataGridCell),
Setters =
{
new Setter
{
Property = DataGridCell.IsSelectedProperty,
Value = new Binding(string.Format("[{0}].IsSelected", i)) { Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged },
}
},
}
});
}
和我的IsSelected属性:
private bool isSelected = false;
public bool IsSelected
{
get
{
return this.isSelected;
}
set
{
this.isSelected = value;
OnPropertyChanged("IsSelected");
}
}
查看您的代码,单元格级别的选择似乎有一个共享源IsSelected
属性,每个单元格都会尝试更新此属性(由于TwoWay
绑定),从而影响共享同一源绑定的所有其他单元格。
您需要为此修改代码。
你能把IsSelected
类的代码放在里面吗?也许我们可以改变数据网格的设置方式。
当我将VirtualizationMode设置为Standard时,它似乎修复了它。
这一建议归功于@Blam,但由于他还没有把它作为答案发布,我正在发布。如果@Blam发布他的回答而不是评论,我会认为这是正确的,但在此之前,我会将其标记为正确的,以帮助未来的用户。