【发布时间】:2012-03-19 18:24:51
【问题描述】:
我正在使用 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");
}
}
【问题讨论】:
-
代码与你之前所说的相矛盾
-
虚拟化应该不是问题,因为创建了控件,然后才应该评估绑定。你能给出具体的步骤来重现这个以及你的绑定代码吗?
-
糟糕,复制了错误的部分代码。 @H.B - 也许它“不应该”是一个问题......但它是!它在虚拟化关闭的情况下工作,在虚拟化打开的情况下不起作用。
-
我的猜测是该属性仅在第一次传递时才被评估,并且仅实际应用于可见单元格。您可以尝试设置 VirtualizationMode = standard 来评估它。但我的猜测可能比我蹩脚的答案更糟糕。
标签: c# wpf data-binding datagrid virtualization