我在从csv粘贴到wpf数据网格时遇到了问题-我遵循了这里的建议
代码执行时没有任何问题-但是,似乎创建了所有新行,但只有第一行填充了数据。数据似乎经常被覆盖,因此剪贴板数据中的最后一项被填充到第一行,所有其他行都是空的。我知道这一定是一个索引问题或什么,但我无法追踪到它。
另外,当我查看网格的bindable集合中的对象时,其中没有一个包含任何数据。列的OnPastingCellClipboardContent中是否有什么地方出错(可能是数据转换)?
任何想法(参见下面的代码)
protected virtual void OnExecutedPaste(object sender, ExecutedRoutedEventArgs args)
{
// parse the clipboard data
List<string[]> rowData = ClipboardHelper.ParseClipboardData();
bool hasAddedNewRow = false;
// call OnPastingCellClipboardContent for each cell
int minRowIndex = Math.Max(Items.IndexOf(CurrentItem), 0);
int maxRowIndex = Items.Count - 1;
int minColumnDisplayIndex = (SelectionUnit != DataGridSelectionUnit.FullRow) ? Columns.IndexOf(CurrentColumn) : 0;
int maxColumnDisplayIndex = Columns.Count - 1;
int rowDataIndex = 0;
for (int i = minRowIndex; i <= maxRowIndex && rowDataIndex < rowData.Count; i++, rowDataIndex++)
{
if (CanUserAddRows && i == maxRowIndex)
{
// add a new row to be pasted to
ICollectionView cv = CollectionViewSource.GetDefaultView(Items);
IEditableCollectionView iecv = cv as IEditableCollectionView;
if (iecv != null)
{
hasAddedNewRow = true;
iecv.AddNew();
if (rowDataIndex + 1 < rowData.Count)
{
// still has more items to paste, update the maxRowIndex
maxRowIndex = Items.Count - 1;
}
}
}
else if (i == maxRowIndex)
{
continue;
}
int columnDataIndex = 0;
for (int j = minColumnDisplayIndex; j < maxColumnDisplayIndex && columnDataIndex < rowData[rowDataIndex].Length; j++, columnDataIndex++)
{
DataGridColumn column = ColumnFromDisplayIndex(j);
column.OnPastingCellClipboardContent(Items[i], rowData[rowDataIndex][columnDataIndex]);
}
}}
发布于 2021-11-23 17:23:07
我遇到了一个类似的问题,我想将从Excel复制的列(在剪贴板中)粘贴到WPF中的数据网格中。我的方法是构造一个datatable,并将datagrid datacontext设置为该datatable。
string s = Clipboard.GetText();
string[] lines = s.Split('\r');
DataTable dt = new DataTable();
string[] fields;
int row = 0;
int col = 0;
foreach (string item in lines)
{
dt.Rows.Add();
fields = item.Split('\t');
foreach (string f in fields)
{
dt.Rows[row][col] = f;
col++;
}
row++;
col = 0;
}https://stackoverflow.com/questions/4118617
复制相似问题