C# 读取数据网格上的当前行

C# 读取数据网格上的当前行,c#,wpf,datagrid,wpf-controls,C#,Wpf,Datagrid,Wpf Controls,我用WPF4.0和datagrid在c中创建了一些应用程序。 我的datagrid绑定到一个对象 我想在输入一行之后进行一些测试,因此,我使用RowEditEnding事件 这是我的密码 private void dataGrid1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) { TableCompte Compte = e.Row.DataContext as TableCompte; if (

我用WPF4.0和datagrid在c中创建了一些应用程序。 我的datagrid绑定到一个对象

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

这是我的密码

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

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

我的错误在哪里

以下是我的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>
这里的问题是,只有从ItemsSource生成项时,才会设置DataContext。DataGrid上应该有ItemsSource绑定。 使用e.Row.Item代替e.Row.DataContext,这将解决您的问题

更新 看起来问题出在铸件部分

TableCompte Compte = e.Row.DataContext as TableCompte;
您应该知道要绑定到DataGrid的类型。 如果您要绑定到ItemsSource,那么您的类应该有m_CompteTaux1、m_CompteTaux2、m_CompteTaux3、m_CompteTaux4等,并强制转换:

var rowDataItem = e.Row.DataContext as YourClass;

谢谢你的回答,但是如果我使用e.Rom.Item,我的对象是空的:-我的问题似乎是一个CAST问题,因为我的DataContext变量是正确的。我的演员阵容如何?