【发布时间】:2017-05-22 19:24:45
【问题描述】:
我希望创建一个自定义 DataGrid,以便用户可以使用弹出输入框将注释附加到每个单元格。目前,我创建了一个继承自 DataGrid 的 CustomDataGrid 类,并带有一个可以添加注释的 ContextMenu。当用户选择添加注释时,我找到选定的单元格,打开一个输入框并返回响应,并将其存储在字符串列表中,其中每个字符串列表代表一行。但是,这并不总是有效,因为有时没有选择单元格,并且我收到一条错误消息:“对象引用未设置为对象的实例。”。我正在考虑创建一个继承自 DataGridCell 的 CustomDataGridCell 类,该类具有自己的 ContextMenu 和注释字符串。问题是,如何将 CustomDataGrid 中的所有单元格设为 CustomDataGridCell?有没有更好的方法来做到这一点?
这是我当前的 CustomDataGrid 类:
public class CustomDataGrid : DataGrid
{
MenuItem miAddNote;
List<List<string>> notes;
public CustomDataGrid()
{
notes = new List<List<string>>();
miAddNote = new MenuItem();
miAddNote.Click += MiAddNote_Click;
miAddNote.Header = "Add a note";
this.ContextMenu = new ContextMenu();
this.ContextMenu.Items.Add(miAddNote);
}
private void MiAddNote_Click(object sender, RoutedEventArgs e)
{
try
{
int rowIndex = this.SelectedIndex;
int colIndex = this.SelectedCells[0].Column.DisplayIndex;
InputBox ib = new InputBox(notes[rowIndex][colIndex]);
if (ib.ShowDialog() == true)
{
notes[rowIndex][colIndex] = ib.Response;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
protected override void OnLoadingRow(DataGridRowEventArgs e)
{
base.OnLoadingRow(e);
int numColumns = this.Columns.Count;
List<string> newRow = new List<string>();
for (int i = 0; i < numColumns; ++i)
{
newRow.Add("");
}
notes.Add(newRow);
}
}
【问题讨论】:
-
Imo 您需要查看的数据网格部分是 DataGridColumn。也许一个 TemplateColumn 已经足够了。 wpf-tutorial.com/datagrid-control/custom-columns
标签: c# .net wpf datagrid datagridcell