单击datagrid行时,它会抛出异常 - WPF C#

时间:2015-04-25 15:19:36

标签: c# wpf datagrid

每当我尝试双击我的数据网格行进行编辑时,我就会抛出一些对我没有任何意义的例外情况。 Hovever,如果我将整个数据网格设置为IsReadOnly为true,我想要有问题,但我需要第二和第三列可编辑。

XAML

 <DataGrid x:Name="clientList" HorizontalAlignment="Left" Height="225" Margin="11,126,0,0" VerticalAlignment="Top" Width="349" IsSynchronizedWithCurrentItem="False" AutoGenerateColumns="False" HorizontalGridLinesBrush="#FFB9B9B9" VerticalGridLinesBrush="#FF8B8B8B" GridLinesVisibility="Horizontal" CellStyle="{StaticResource Body_Content_DataGrid_Centering}">
        <DataGrid.Resources>
            <LinearGradientBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" StartPoint="0,0" EndPoint="0,1" >
                <GradientStop Color="#66240000" Offset="0"/>
                <GradientStop Color="#CC240000" Offset="0.65"/>
            </LinearGradientBrush>
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridTextColumn Width="30" Header="Id" IsReadOnly="True" Binding="{Binding Id}"/>
            <DataGridTextColumn Width="100" Header="Company" IsReadOnly="False" Binding="{Binding Company}"/>
            <DataGridTextColumn Width="130" Header="Name, Surname" IsReadOnly="False" Binding="{Binding Name}"/>
            <DataGridTemplateColumn Header="Actions" CellTemplate="{StaticResource myTemplate}"/>
        </DataGrid.Columns> 
    </DataGrid>

C#

clientList.Items.Add(new DataClients { Id = 1, Company = "My Company", Name = "Jane Roe"});

例外

Exception:Thrown: "'EditItem' is not allowed for this view."(System.InvalidOperationException)

Exception:Thrown: "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0." (System.FormatException)

1 个答案:

答案 0 :(得分:0)

您应该使用ObservableCollection<DataClients>()作为Datagrid的来源,而不是直接将项目添加到DataGrid。为此,您需要创建一个属性ObservableCollection<DataClients> Data,并将其用作ItemsSource中的DataGrid,例如ItemsSource="{Binding MyBikesOrders}"。然后,您可以将项目添加到ObservableCollection,更新DataGrid,您应该可以直接在其中修改条目。

Here与你的问题非常相似。