WPF DataGrid 可编辑单元格,带有直接放置的项目

WPF DataGrid editable cells with Items put directively

所以,我有一个 DataGrid,我想以编程方式对其进行大量操作。

string[] values = new string[something.Count];
for (int i = 0; i < somethingElse.Count; i++)
{
    if (condition)
        values[i] = Data[i].ToString();
    else
        values[i] = "";
}

var style = new System.Windows.Style(typeof(DataGridRowHeader));
style.Setters.Add(new Setter(DataGridRowHeader.ContentProperty, Data[0].ToString()));

MyGrid.Items.Add(new DataGridRow()
{
    HeaderStyle = style,
    Item = values
});

这是我循环执行的,我可以用我需要的所有数据填充我的网格。 之后,我可以访问单元格,编辑它们,获取它们的值,无论我想要和需要什么。 但是,当用户想要像在 MS Excel 中那样使用网格时,单元格不可编辑。

所以我反其道而行之,创建了一个 :

ObservableCollection<ObservableCollection<string>> gridData = new ObservableCollection<ObservableCollection<string>>();

//*** ... *** the gridData is filled in the same way, you can imagine

MyGrid.ItemsSource = gridData;

这确实以完全相同的方式填写数据,不仅如此,数据现在是可编辑的。 但是我的自定义行 headers 消失了。 我需要它们,而且,我不认为我想对行 header 值使用绑定。

能否以某种方式修改第一种方法使其仍然可编辑,但以完全相同的方式填充数据行?

我最终结合上述两种方法解决了这个问题。 首先,我生成 ObservableCollection<ObservableCollection<string>> dataCollection,用数据填充它。

接下来我生成一个 ObservableCollection<DataGridRow> rowCollection 集合。

在第一种方法的循环声明部分,您可以在问题中看到,我这样做

rowCollection.Add(new DataGridRow()
{
    HeaderStyle = style,
    Item = dataCollection[i]   //for the corresponding iteration element
});

这一切在设置

时结束
MyGrid.ItemsSource = rowCollection;

到目前为止(测试时间很少),这似乎是我一直在寻找的东西,希望它也能帮助其他人。