编辑一个空白的数据网格wpf

时间:2017-03-27 09:44:27

标签: c# wpf datagrid

我正在添加一个空白的数据网格,以允许用户向其添加自己的信息,但是当我点击编辑用户通过按钮点击事件添加的字段时,我得到了可怕的' EditItem& #39;此视图不允许使用此视图。我已经通过这个错误查看了类似的问题,但是我的生活无法解决我的问题。我理解这与没有为datagrid设置itemsource有关,但我不知道我可以添加它来解决我的问题。希望有人可以告诉我我的方式的错误。一如既往地感谢您的帮助。

XAML

<Grid>
    <DataGrid x:Name="ResultsDataGrid" HorizontalAlignment="Left" Margin="87,356,0,0" VerticalAlignment="Top" Height="134" Width="835" IsReadOnly="False" CanUserAddRows="True" CanUserDeleteRows="True">
        <DataGrid.Columns>
            <DataGridTextColumn x:Name="StationID" Header="Station ID"/>
            <DataGridTextColumn x:Name="Pointnumber" Header="Point Number"/>
            <DataGridTextColumn x:Name="Description" Header="Description"/>
            <DataGridTextColumn x:Name="Velocity" Header="Velocity (MilliSeconds)"/>
            <DataGridTextColumn x:Name="Status" Header="Status"/>
        </DataGrid.Columns>
    </DataGrid>
    <Button x:Name="AddResult" Content="Add Result" HorizontalAlignment="Left" Margin="752,495,0,0" VerticalAlignment="Top" Width="75" Click="AddResult_Click"/>
    <Button x:Name="RemoveResult" Content="Remove Result" HorizontalAlignment="Left" Margin="832,495,0,0" VerticalAlignment="Top" Width="90" Click="RemoveResult_Click"/>
</Grid>

C#
using System.Collections.Generic;
using System.Windows;

namespace DataGridTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        public class AddResultRow
        {
            public string StationID { get; set; }
            public string Pointnumber { get; set; }
            public string Description { get; set; }
            public string Velocity { get; set; }
            public string Status { get; set; }
        }

        private List<AddResultRow> addnewrow()
        {
            List<AddResultRow> result = new List<AddResultRow>();
            result.Add(new AddResultRow()
            {
                StationID = "",
                Pointnumber = "",
                Description = "",
                Velocity = "",
                Status = ""
            });

            return result;
        }

        private void AddResult_Click(object sender, RoutedEventArgs e)
        {
            ResultsDataGrid.Items.Add(addnewrow());
        }

        private void RemoveResult_Click(object sender, RoutedEventArgs e)
        {
            var selectedItem = ResultsDataGrid.SelectedItem;
            if (selectedItem != null)
            {
                ResultsDataGrid.Items.Remove(selectedItem);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您希望能够编辑项目,请不要将对象添加到<startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/> </startup> 的{​​{1}}集合中。相反,您应该将Items属性设置为DataGrid并向此项添加项目:

ItemsSource