如何在单击WPF DataGrid时修复“未处理的异常”?

时间:2011-08-18 19:54:01

标签: c# wpf c#-4.0 wpf-controls

我正在使用Visual Studio 2010,WPF和C#4.0,当单击DataGrid中的单元格时,我得到以下异常:

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll  Additional information: A TwoWay or OneWayToSource binding cannot work on the read-only property 'Column2' of type 'VindecoderUI.AcesData'.

这是我的代码:

    <DataGrid AutoGenerateColumns="False" Height="190" Name="nadaDataGrid" Width="304" FrozenColumnCount="1000" ItemsSource="{Binding Source={StaticResource nadaDataCollection}}" CanUserReorderColumns="False" CanUserResizeColumns="True" CanUserSortColumns="False" AlternatingRowBackground="#3F000000" CanUserResizeRows="False" SelectionMode="Single" SelectionUnit="Cell"
               SelectionChanged="dataGrid1_SelectionChanged" AreRowDetailsFrozen="True" >
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=NadaSeries}" Header="Nada Series" />
            <DataGridTextColumn Binding="{Binding Path=NadaBS}" Header="Nada BS" />
            <DataGridTextColumn Binding="{Binding Path=MSRP}" Header="MSRP" />
            <DataGridTextColumn Binding="{Binding Path=GVWR}" Header="GVWR" />
            <DataGridTextColumn Binding="{Binding Path=GCWR}" Header="GCWR" />
        </DataGrid.Columns>
    </DataGrid>

    <Window.Resources>
    <CollectionViewSource x:Key="nadaDataCollection"></CollectionViewSource>
    <CollectionViewSource x:Key="acesDataCollection"></CollectionViewSource>
</Window.Resources>

1 个答案:

答案 0 :(得分:10)

默认情况下,DataGrid单元格是可编辑的(这意味着绑定为TwoWay。)由于您绑定的项目包含具有只读属性的项目,因此单击时会出现异常在单元格上,因为编辑无法工作。

您应该可以通过将Mode=OneWay添加到该字段的列绑定来解决此问题。