仅当 isReadOnly 为 false 时才转换为模型时出现 Datagrid 错误?
Datagrid error when casting to model only when isReadOnly is false?
我有 Datagrid,我想将每一行的数据转换为特定模型。
铸造代码是
private List<SearchAndReplaceModel> getSelectedWordes()
{
DGKeywords.UnselectAllCells();
var repo = new SearchAndReplaceRepository();
List<SearchAndReplaceModel> selectedWordes = new List<SearchAndReplaceModel>();
List<SearchAndReplaceModel> dataFromGrid=DGKeywords.Items.Cast<SearchAndReplaceModel>().ToList();
if (dataFromGrid != null)
for (int i = 0; i < dataFromGrid.Count; i++)
{
selectedWordes.Add ( dataFromGrid[i]);
}
return selectedWordes;
}
奇怪的是,当 Datagrid isReadOnly=true
的 属性 时代码运行完美,但当我将其更改为 isReadOnly=false
时出现异常
异常:
Exception thrown: 'System.InvalidCastException' in System.Core.dll An exception of type 'System.InvalidCastException' occurred in System.Core.dll but was not handled in user code Unable to cast object of type 'MS.Internal.NamedObject'
使用 .OfType()
扩展方法而不是 .Cast()
:
private List<SearchAndReplaceModel> getSelectedWordes()
{
DGKeywords.UnselectAllCells();
return DGKeywords.Items.OfType<SearchAndReplaceModel>().ToList();
}
或者迭代 DGKeywords.ItemsSource
可能更简单(取决于 DataGrid 填充数据的方式)
我有 Datagrid,我想将每一行的数据转换为特定模型。 铸造代码是
private List<SearchAndReplaceModel> getSelectedWordes()
{
DGKeywords.UnselectAllCells();
var repo = new SearchAndReplaceRepository();
List<SearchAndReplaceModel> selectedWordes = new List<SearchAndReplaceModel>();
List<SearchAndReplaceModel> dataFromGrid=DGKeywords.Items.Cast<SearchAndReplaceModel>().ToList();
if (dataFromGrid != null)
for (int i = 0; i < dataFromGrid.Count; i++)
{
selectedWordes.Add ( dataFromGrid[i]);
}
return selectedWordes;
}
奇怪的是,当 Datagrid isReadOnly=true
的 属性 时代码运行完美,但当我将其更改为 isReadOnly=false
异常:
Exception thrown: 'System.InvalidCastException' in System.Core.dll An exception of type 'System.InvalidCastException' occurred in System.Core.dll but was not handled in user code Unable to cast object of type 'MS.Internal.NamedObject'
使用 .OfType()
扩展方法而不是 .Cast()
:
private List<SearchAndReplaceModel> getSelectedWordes()
{
DGKeywords.UnselectAllCells();
return DGKeywords.Items.OfType<SearchAndReplaceModel>().ToList();
}
或者迭代 DGKeywords.ItemsSource
可能更简单(取决于 DataGrid 填充数据的方式)