重用的DataGrid控件值重复使用

时间:2013-10-16 08:31:47

标签: c# wpf datagrid virtualization

问题是,当我以编程方式编辑datagrid中的列值并向下滚动时,这些值会在列的下一个单元格中重复显示。这似乎是虚拟化错误或“效果”,因为当我关闭它时,问题就消失了。我认为问题出在这个地方:

public void EditedCell(object oItem, string oColumnName, ref List<string> lErrors, object newValue = null)
{
    DataGridRow dgRow = dgDati.ItemContainerGenerator.ContainerFromItem(oItem) as DataGridRow;
    /* In other places, when I call EditedCell(DataGridRow, ...) it works fine.
       The problem shows up only when I call EditedCell(object oItem, ...) */
    EditedCell(dgRow, oColumnName, ref lErrors, newValue);
}

这是问题的屏幕。由于此问题,黄色单元格以编程方式更改,并显示其他包含0000的单元格。当我从DataSource读取数据时,它在DataRows中没有那些0000值:

enter image description here

另外,要设置单元格的值,我在单元格和DataRow值中设置单元格控件以更改值并正确显示:

if (oElement.GetType() == typeof(TextBox))
{
    (oElement as TextBox).Text = newValue.ToString();
}

if (oElement.GetType() == typeof(TextBlock))
{
    (oElement as TextBlock).Text = newValue.ToString();
}

有没有人见过类似的东西,知道怎么处理?

1 个答案:

答案 0 :(得分:1)

不要通过程序代码操纵WPF控件。这不是WPF way。在WPF中,您应该操纵绑定到UI的数据,而不是直接操作UI。这种设计模式被称为MVVM,可以让您免除这一切。