【问题标题】:Reading current line on a DataGrid读取 DataGrid 上的当前行
【发布时间】:2012-09-02 20:20:07
【问题描述】:

我在 c# 中使用 WPF 4.0 和一个数据网格创建了一个小应用程序。 我的数据网格绑定到一个对象。

我想在输入一行后进行一些测试,所以我使用 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>

【问题讨论】:

    标签: c# wpf datagrid wpf-controls


    【解决方案1】:

    这里的问题是 DataContext 只有在项目是从 ItemsSource 生成时才会设置(DataGrid 上应该有 ItemsSource 绑定)。
    而不是e.Row.DataContext 使用e.Row.Item,这将解决您的问题。


    更新

    看起来问题出在演员阵容中。

    TableCompte Compte = e.Row.DataContext as TableCompte;
    

    您应该知道要绑定到DataGrid 的类型。 如果您将ObservableCollection&lt;YourClass&gt; FooObservable 绑定到ItemsSource,那么YourClass 应该有m_CompteTaux1、m_CompteTaux2、m_CompteTaux3、m_CompteTaux4 等。然后进行转换:

    var rowDataItem = e.Row.DataContext as YourClass;
    

    【讨论】:

    • 感谢您的回答,不过如果我使用 e.Rom.Item,我的对象为 null :-(
    • 看来我的问题是 CAST 问题,因为我的 DataContext 变量是正确的。如何纠正我的演员表?
    猜你喜欢
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    相关资源
    最近更新 更多