【问题标题】:Making a DataGrid Editable in WPF在 WPF 中使 DataGrid 可编辑
【发布时间】:2012-01-21 05:26:13
【问题描述】:

我试图使 dataGrid1 可编辑。我读到我可以为 List 创建一个类实例,然后将其分配给 DataGrid.ItemSource。这可能只有 2 行代码,但仍然不知道如何使用下面的代码来做到这一点。有任何想法吗?谢谢!

public class MyData
{
    public string street { set; get; }
    public string town { set; get; }
}

DataGridTextColumn col1 = new DataGridTextColumn();
col1.Binding = new Binding("name");
dataGrid1.Columns.Add(col1);
dataGrid1.Items.Add((new MyData() { street = "5th ave", town = "neverland"}));

好的,感谢您的帮助。仍在尝试习惯在 stackoverflow 上发帖。这是我所做的更改,并且对我有用。

List<MyData> MyListBox1 =new List<MyData>();
MyListBox1.Add(new MyData() { street = "5th ave", town = "neverland"}));
List<MyData> MyListBox1 =new List<MyData>();

我也必须添加

使用 System.Collections.Generic;

【问题讨论】:

    标签: wpf datagrid


    【解决方案1】:

    这是你想要的吗? 在您的 XAML 代码中

          <DataGrid AutoGenerateColumns="False" Name="dataGrid1">
             <DataGrid.Columns>
                <DataGridTextColumn Header="Street" Binding="{Binding street}"/>
                <DataGridTextColumn Header="Town" Binding="{Binding town}"/>  
                <!-- by defect is editable -->
    
                <DataGridTextColumn Header="Town" Binding="{Binding town}" IsReadOnly="True"/>  
                <!-- Not editable -->
    
                ... more properties
             </DataGrid.Columns>
          </DataGrid>
    

    在您的班级中,仅将 List(Any enumerable) 与 DataGrid 绑定

          public MyClass
          {
               InitializeComponent();
               List<MyData> lstData = new List<MyData>();
               dataGrid1.ItemsSource = lstData;
          }
    

    您可以编辑您的 DataGrid,每个项目都将添加到列表中

    【讨论】:

    • 谢谢。我远离 XAML 只是为了看看我是否可以在代码中做所有事情。我必须首先使用 System.Collections.Generic 分配一个指令才能使用列表,然后必须在我的情况下将 List 1stData 或 myList 定义为主类结构中的公共。最后,新添加的内容并没有刷新,所以我必须在添加新项目后运行 dataGrid1.Items.Refresh() 。再次感谢!
    【解决方案2】:

    好吧,您没有分配ItemsSource,而是将一个项目添加到Items 集合中,这是完全不同的事情。

    (另外,如果没有这样的属性,你为什么要绑定到name?)

    【讨论】:

    • 嗯,我重新设计了这个项目。我将在下面的代码中向您展示我最终做了什么。谢谢。
    • @MichaelDietz:请在上面而不是下面,cmets 不适合代码。
    【解决方案3】:

    让您的 ItemsSource 作为 ObservableCollection 完美运行 ObservableCollection itmSrcLevels = new ObservableCollection(ItemsSrc1);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 2013-07-30
      • 2011-03-26
      • 2014-10-10
      • 1970-01-01
      • 2012-11-21
      相关资源
      最近更新 更多