如何使用其列和行索引值设置datagrid单元格的值?

时间:2011-10-12 08:41:01

标签: c# wpf datagrid

如何使用cells列和行索引将值插入特定的datagrid单元格。我将行和列索引保存为整数。

我得到的索引如下。我基本上采用单元格值,列索引和行索引,并作为序列化XML发送到java发送回来,需要将它放在同一个单元格中。

        int column = dataGrid2.CurrentCell.Column.DisplayIndex;
        int row = dataGrid2.SelectedIndex;

谢谢,

4 个答案:

答案 0 :(得分:1)

对于数据网格,您可以通过Items属性访问行。单元格是项目的集合。

dataGrid2.Items[row].Cells[column].Text = "text";

只要数据在当前页面生命周期中绑定到数据网格,就可以正常工作。如果情况并非如此,那么我相信你会陷入困境。

答案 1 :(得分:1)

要以编程方式更新WPF DataGridCell,可能有很多方法......

其中一种方法是更新绑定数据项本身的值。这样,属性更改通知将触发所有订阅的视觉效果,包括DataGridCell本身......

反思方法

 var boundItem = dataGrid2.CurrentCell.Item;

 //// If the column is datagrid text or checkbox column
 var binding = ((DataGridTextColumn)dataGrid2.CurrentCell.Column).Binding;

 var propertyName = binding.Path.Path;
 var propInfo = boundItem.GetType().GetProperty(propertyName);
 propInfo.SetValue(boundItem, yourValue, new object[] {});

对于DataGridComboBoxColumn,您必须提取SelectedValuePath并使用它代替propertyName

其他包括将单元格置于编辑模式并使用EditingElementStyle中的某些行为更新其内容值...我发现这很麻烦。

如果你确实需要,请告诉我。

答案 2 :(得分:1)

我使用了一个基于WPF的变体 - 它的例子来做整行并且它有效!:

(sender as DataGrid).RowEditEnding -= DataGrid_RowEditEnding;

foreach (var textColumn in dataGrid2.Columns.OfType<DataGridTextColumn>())
            {
                var binding = textColumn.Binding as Binding;
                if (binding != null)
                {
                    var boundItem = dataGrid2.CurrentCell.Item;
                    var propertyName = binding.Path.Path;
                    var propInfo = boundItem.GetType().GetProperty(propertyName);
                    propInfo.SetValue(boundItem, NEWVALUE, new object[] { });
                }
            }

(sender as DataGrid).RowEditEnding += DataGrid_RowEditEnding;

PS:确保使用对列有效的值类型(可能通过switch语句)。

例如为: 切换propertyName或propInfo ... propInfo.SetValue(boundItem,(type)NEWVALUE,new object [] {});

                    switch (propertyName)
                    {
                        case "ColumnName":
                            propInfo.SetValue(boundItem, ("ColumnName"'s type) NEWVALUE, new object[] { });
                            break;
                        default:
                            break;
                    }

答案 3 :(得分:0)

如果您使用DataGrid,则可以尝试

DataRowView rowView = (dtGrid.Items[rows] as DataRowView); //Get RowView
rowView.BeginEdit();
rowView[col] = "Change cell here";
rowView.EndEdit();
dtGrid.Items.Refresh(); // Refresh table