2012-09-02 24 views
1

我在c#中用WPF 4.0和一個數據網格創建了一個小應用程序。 我的datagrid綁定到一個對象。讀取DataGrid上的當前行

我想在輸入一行後做一些測試,所以我使用RowEditEnding事件。

這裏是我的代碼

private void dataGrid1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) 
{ 
    TableCompte Compte = e.Row.DataContext as TableCompte; 

    if (Compte != null) 
    { 
     // Verifs 
    } 
} 

我的問題是我的對象爲null。

我的錯誤在哪裏?

這裏是我的XAML聲明:

<DataGrid AutoGenerateColumns="false" Name="dataGrid1" AreRowDetailsFrozen="false" Margin="31,227,28,82" RowEditEnding="dataGrid1_RowEditEnding"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Width="134" Header="Compte d'origine" Binding="{Binding Path=m_CompteOrigine, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 
     <DataGridTextColumn Width="134" Header="Compte Taux 1" Binding="{Binding Path=m_CompteTaux1, Mode=TwoWay ,UpdateSourceTrigger=PropertyChanged}" /> 
     <DataGridTextColumn Width="134" Header="Taux 1" Binding="{Binding Path=m_Taux1, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged }" /> 
     <DataGridTextColumn Width="134" Header="Compte Taux 2" Binding="{Binding Path=m_CompteTaux2, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" /> 
     <DataGridTextColumn Width="134" Header="Taux 2" Binding="{Binding Path=m_Taux2, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged }" /> 
     <DataGridTextColumn Width="134" Header="Compte Taux 3" Binding="{Binding Path=m_CompteTaux3, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" /> 
     <DataGridTextColumn Width="134" Header="Taux 3" Binding="{Binding Path=m_Taux3, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged }" /> 
    </DataGrid.Columns> 
</DataGrid> 

回答

0

這裏的問題是,DataContext將只有從ItemsSource生成項目設置(應該有ItemsSourceDataGrid綁定)。
而不是e.Row.DataContext使用e.Row.Item這將解決您的問題。


更新

正如它出現問題是在鑄造部。

TableCompte Compte = e.Row.DataContext as TableCompte; 

您應該知道您綁定的類型DataGrid。 如果你結合ObservableCollection<YourClass> FooObservableItemsSource然後YourClass應該有m_CompteTaux1,m_CompteTaux2,m_CompteTaux3,m_CompteTaux4等鑄造:

var rowDataItem = e.Row.DataContext as YourClass; 
+0

謝謝您的回答,不過如果我用e.Rom.Item,我的對象爲空:-( –

+0

看來我的問題是一個CAST問題,因爲我的DataContext變量是正確的。 –