2016-03-23 18 views
0

我用RowEditEnding事件DataGrid中獲得更新的行和回報TextBlock的在C#中RowEditEnding得到一個空值在DataGrid中

private void OnUpdateOrInsertItem(object sender,DataGridRowEditEndingEventArgs e) 
    { 
     DataGridRow row1 = e.Row; 

     int row_index = ((DataGrid)sender).ItemContainerGenerator.IndexFromContainer(row1); 
     int numberOfColumns = ((DataGrid)sender).Columns.Count; 
     DataGridCell RowColumn = ((DataGrid)sender).Columns[1].GetCellContent(row1).Parent as DataGridCell; 
     string CellValue = ((TextBlock)RowColumn.Content).Text; 
     MessageBox.Show(CellValue); 
    } 

更新我的數據庫,但是當我改變細胞,我打印出來的消息框,它在messageBox上返回一個空值。 我認爲有關線程 的問題,這是我的XML代碼

<Grid> 
    <DataGrid x:Name="datagrid1" AutoGenerateColumns="true" HorizontalAlignment="Left" Margin="0,55,0,0" VerticalAlignment="Top" Height="248" Width="672" RowEditEnding="OnUpdateOrInsertItem" PreviewKeyDown="OnDeleteItem"/> 
    <Button Content="Show Database" HorizontalAlignment="Left" Margin="54,10,0,0" VerticalAlignment="Top" Width="98" RenderTransformOrigin="-0.193,-13.506" Height="29" Click="Button_Click_1"/> 
    <ComboBox x:Name="comboBox1" SelectedIndex="0" HorizontalAlignment="Left" Margin="469,17,0,0" VerticalAlignment="Top" Width="120" Loaded="ComboBox_Loaded" 
    SelectionChanged="ComboBox_SelectionChanged"/> 
</Grid> 

我怎麼能解決這個問題,如果有另一種方式在RowEditEnding事件獲得更新的行?

回答

0
  1. 使用data binding(和templating,這裏由數據網格自動完成)。然後更新後的值將在您的綁定(視圖)模型中,而不需要使用該事件。
  2. 請勿使用ItemContainerGenerator。如果您需要訪問UI項目,請將相關屬性綁定到基礎視圖模型。