XAML 如何在uwp中用datatable填充datagrid并使其可编辑?

esyap4oy  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(162)

需要在UWP中使用Datatable填充Datagrid。我可以通过以下方式显示内容:https://stackoverflow.com/a/53767049/12053338
但是,我无法编辑数据网格。
如何使数据网格可编辑?(已厌倦将IsReadOnly设置为false)。
谢谢
XAML语言

<controls:DataGrid
                        x:Name="grid" 
                        IsReadOnly="False"
                        VerticalAlignment="Stretch" 
                        HorizontalAlignment="Stretch"
                        GridLinesVisibility="All">

        </controls:DataGrid>

C#

//Datatable
            var table = new DataTable("Students");
            table.Columns.Add(new DataColumn() { ColumnName = "Name", DataType = typeof(string)});
            table.Columns.Add(new DataColumn() { ColumnName = "Id", DataType = typeof(string)});

            //Add a row
            table.Rows.Add("Akinator","1");

          //Conversion of datatable to datagrid itemsource
          for (int i = 0; i < table.Columns.Count; i++)
            {
                grid.Columns.Add(new DataGridTextColumn()
                {
                    Header = table.Columns[i].ColumnName,
                    Binding = new Binding { Path = new PropertyPath("[" + i.ToString() + "]"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }

                });
            }
            var collection = new ObservableCollection<object>();
            foreach (DataRow row in table.Rows)
            {
                if (row.ItemArray.Length > 0)
                    collection.Add(row.ItemArray);

            }
            grid.ItemsSource = collection;
  • 在此特定情况下,数据表的使用不可替代。
ogq8wdun

ogq8wdun1#

我已经找到了这个问题的解决方案,在创建列时将IsReadonly设置为false

//Conversion of datatable to datagrid itemsource
      for (int i = 0; i < table.Columns.Count; i++)
        {
            grid.Columns.Add(new DataGridTextColumn()
            {
                Header = table.Columns[i].ColumnName,
                Binding = new Binding { Path = new PropertyPath("[" + i.ToString() + "]"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged },
                IsReadOnly = false //ADD THIS TO MAKE THE DATAGRID EDITABLE

            });
        }
        var collection = new ObservableCollection<object>();
        foreach (DataRow row in table.Rows)
        {
            if (row.ItemArray.Length > 0)
                collection.Add(row.ItemArray);

        }
        grid.ItemsSource = collection;

相关问题