2012-09-03 55 views
0

我在c#中用WPF 4.0和一个数据网格创建了一个小应用程序。 我的数据网格绑定到某些“数据表”组件的数据成员CAST DataGridView错误

我想在输入一行后做一些测试,所以我使用RowEditEnding事件。

这里是我的代码

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

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

我的问题是我的目标 “孔特” 为空。

不过,我的“DataContext”价值很不错!所以这是一个演员错误,但我的错误在哪里?

这里是我的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> 

感谢很多:)

+1

调试器?检查'e.Row.DataContext'? –

+0

什么是dataGrid1的ItemsSource?它是一个数据表? –

+0

e.row.dataContext是正确的!这就是为什么我知道这是一个Cast Error。 –

回答

1

e.Row.DataContext包含的行,而不是DataGrid的数据源的项目源。

因此它将会是以前的所有,包括m_CompteOrigine,m_CompteTaux1,m_CompteTaux2等。
它们是否都具有相同的类型或接口?

您应该转换为项目源的公共类型/接口。

假设:

Compte m_CompteOrigine; 
Compte m_CompteTaux1; 

然后做:

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

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

如果您仍然有问题。尝试调试并在赋值语句中设置断点。然后使用调试器检查e.Row.DataContext;它会告诉你它的类型。

祝你好运