C# DataGridView上的强制转换错误

C# DataGridView上的强制转换错误,c#,wpf,datagridview,C#,Wpf,Datagridview,我用WPF4.0和datagrid在c#中创建了一些应用程序。 我的datagrid绑定到“TableCompte”对象的一些数据成员 我想在输入一行之后进行一些测试,因此,我使用RowEditEnding事件 这是我的密码 private void dataGrid1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) { TableCompte Compte = e.Row.DataContext as Tab

我用WPF4.0和datagrid在c#中创建了一些应用程序。 我的datagrid绑定到“TableCompte”对象的一些数据成员

我想在输入一行之后进行一些测试,因此,我使用RowEditEnding事件

这是我的密码

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

    if (Compte  != null)
    {
       // Verifs
    }
}
我的问题是我的对象“Compte”为空

不过,我的“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>


非常感谢:)

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

因此,它将是
mu CompteOrigine
mu CompteTaux1
mu 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
;它会告诉你它的类型


祝你好运

?检查
e.Row.DataContext
?dataGrid1的项目来源是什么?它是数据表吗?e.row.dataContext是正确的!这就是为什么我知道这是一个强制转换错误。我没有在我的DataGrid上设置itemsSource(你可以在我的XAML代码上看到它)检查
DataContext的类型。它实际上是
TableCompte
类型吗?