我有 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'
uj5u.com熱心網友回復:
使用.OfType()擴展方法而不是.Cast():
private List<SearchAndReplaceModel> getSelectedWordes()
{
DGKeywords.UnselectAllCells();
return DGKeywords.Items.OfType<SearchAndReplaceModel>().ToList();
}
或者迭代可能更簡單DGKeywords.ItemsSource(取決于 DataGrid 是如何填充資料的)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/458847.html
上一篇:C#WPF-我如何動態地創建一個帶有動態列的DataGrid(每列的存在取決于用戶輸入)
下一篇:C#mvvm如何處理視窗關閉事件
