首先,我正在學習,所以請不要對我太苛刻,拜托。我有一個從資料庫中獲取資料的 DataGrid,我想添加 ContextMenu 以獲取第一列 (Id),以便我可以對資料庫使用洗掉操作。我搜索了一下,最后得到了這個代碼:
用于添加 ConextMenu XML
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="delete" Click="BtnFactorDell">
<MenuItem.Icon>
<Image Width="12" Height="12" Source="img/delete.png"/>
</MenuItem.Icon>
</ContextMenu>
</DataGrid.ContextMenu>
為了選擇我的 id 的第一個 colomn,我使用了這個:
string factorselectedid;
private void FactorGrid_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
object item = FactorGrid.SelectedItem;
factorselectedid = (FactorGrid.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
}
現在我有 1 個問題和 1 個問題,首先關于問題是最后那個 TextBlock 是什么?因為它是我通過搜索找到的代碼中的 TexBox 并且出現了一些錯誤,所以我隨機將其更改為 TextBlock 并且它作業正常!現在我對這是什么感到困惑。
關于我的問題是當我點擊 DataGridview 上的空白區域時,它給了我錯誤:
System.ArgumentOutOfRangeException: '指定的引數超出了有效值的范圍。引數名稱:索引'
在線上
factorselectedid = (FactorGrid.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
只有單擊檔案而不是 Datagrid 的空白空間,我才能做什么?謝謝你。
uj5u.com熱心網友回復:
最后那個 TextBlock 是什么?
GetCellContent(item)回傳FrameworkElement,但 FrameworkElement 沒有Text屬性。在你的情況下,回傳的東西是一個(派生的)a TextBlock,它是一個FrameworkElement(TextBlock 派生自 FrameworkElement),但要訪問Text你必須將回傳的屬性FrameworkElement轉換為TextBlock第一個
您可能已經看到了轉換為TextBox; 的示例。如果被轉換的東西實際上是 aTextBox - 在你的情況下它不是 aTextBox但它是 a TextBlock(或其他源自 的東西TextBlock),那么這些示例將起作用,因此可以TextBlock正常作業。
System.ArgumentOutOfRangeException: '指定的引數超出了有效值的范圍。引數名稱:索引'
您只是直接嘗試訪問第一個單元格 ( [0]),SelectedCells而根本不知道是否有任何選定的單元格;如果沒有選中的單元格,你會遇到問題
考慮在嘗試訪問之前檢查是否至少有 1 個單元格:
if(FactorGrid.SelectedCells.Count > 0)
factorselectedid = (FactorGrid.SelectedCells[0].Column.GetCellContent(item) as TextBlock)?.Text;
else
e.Handled = true; //suppress the context menu from opening at all
我之前也添加?過.Text- 如果它不是TextBlock,它將防止崩潰,但這將意味著factorselectedid最終null. 任何使用的代碼都factorselectedid應該檢查它是否為空first
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/357661.html
下一篇:異步函式凍結UI執行緒
