C# 在WPF中使用DataGrid的“AlternationCount”属性
我对DataGrid的AlternationCount属性有问题。 我为行的背景设置了两种颜色,现在当我选择其中一行并移动滚动条时,每隔一行也会被选中! 我已经设置了AlternationCount=2和SelectionMode=Single 谁能解决这个问题 C代码:C# 在WPF中使用DataGrid的“AlternationCount”属性,c#,wpf,datagrid,C#,Wpf,Datagrid,我对DataGrid的AlternationCount属性有问题。 我为行的背景设置了两种颜色,现在当我选择其中一行并移动滚动条时,每隔一行也会被选中! 我已经设置了AlternationCount=2和SelectionMode=Single 谁能解决这个问题 C代码: private void Window_Loaded(object sender, RoutedEventArgs e) { var data1 = new Test { Test1 = "Te
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var data1 = new Test { Test1 = "TestCell1", Test2 = "TestCell2", Test3 = "TestCell3" };
var data2 = new Test { Test1 = "TestCell1", Test2 = "TestCell2", Test3 = "TestCell3" };
for (int i = 0; i < 10; i++)
{
dataGrid1.Items.Add(data1);
dataGrid1.Items.Add(data2);
}
}
public class Test
{
public string Test1 { get; set; }
public string Test2 { get; set; }
public string Test3 { get; set; }
}
Xaml:
请看下面的代码:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
dataGrid1.Items.Add(new Test { Test1 = "TestCell1", Test2 = "TestCell2", Test3 = "TestCell3" });
dataGrid1.Items.Add(new Test { Test1 = "TestCell1", Test2 = "TestCell2", Test3 = "TestCell3" });
}
}
对象data1被分配给dataGrid1 10次。单击数据行时,gridcontrol使用equal方法检查每一行。您没有在测试类中实现equals,这意味着您的对象在其引用相等时是相等的,这种情况是因为您为同一对象分配了相同的引用10次
进一步资料来自:
如果当前实例是引用类型,EqualsObject方法将测试引用相等性,对EqualsObject方法的调用相当于对ReferenceEquals方法的调用。引用相等意味着被比较的对象变量引用同一个对象
实施IEquatable:
要检查一个对象是否等于另一个对象,可以使用IEquatable接口,如下所示:
var data1 = new Test { Test1 = "TestCell1", Test2 = "TestCell2", Test3 = "TestCell3" };
public class Test : IEquatable<Test>
{
public string Test1 { get; set; }
public string Test2 { get; set; }
public string Test3 { get; set; }
public bool Equals(Test other)
{
if (other == null) return false;
return Test1.Equals(other.Test1)
&& Test2.Equals(other.Test2)
&& Test3.Equals(other.Test3);
}
}
通过覆盖equals方法,您将覆盖默认的均衡行为,该行为通过引用检查两个对象是否相等。当涉及滚动时,也会发生UI虚拟化。谢谢。你的回答解决了我的问题。但有一个问题:为什么在滚动后选择了多行,而我设置了SelectionMode=Single?因为对象实际上是相等的,所以选择了多个项目。SelectionModel Single通过均衡对象来搜索对象的整个对象列表。如果找到多个相等的对象,则选择这些对象。我不知道wpf正在使用的内部滚动行为,可能滚动后会重新选择项目。不过我不确定。
public class Test : IEquatable<Test>
{
public string Test1 { get; set; }
public string Test2 { get; set; }
public string Test3 { get; set; }
public bool Equals(Test other)
{
if (other == null) return false;
return Test1.Equals(other.Test1)
&& Test2.Equals(other.Test2)
&& Test3.Equals(other.Test3);
}
}