如何创建dataGridViewComboBoxCell并将其添加到dataGrid

时间:2014-01-28 13:39:04

标签: c# wpf datagrid datagridviewcombobox

我正在尝试创建一个WPF应用程序。在我的应用程序中,我想在我的dataGrid的3行中添加一个ComboboxCell。

我可以使用以下代码在C#窗口应用程序中执行此操作:

public partial class Form1 : Form
{
    public Form1()
    {
           InitializeComponent();
           for (int i = 1; i < 13; i++)
           {
                 dataGridView1.Columns.Add("Slot" + i, "Slot " + i);
           }
           for (int i = 0; i < 18; i++) 
           {
                dataGridView1.Rows.Add();
           }GridBaseCells();
    }
    DataGridViewComboBoxCell ModeCell  = new DataGridViewComboBoxCell();
    string[] Modes= { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
    void GridBaseCells()
    {
         ModeCell.Items.AddRange(ModeAr);
         for (int i = 2; i < 14; i++)
         {
              dataGridView1[i, 3] = (DataGridViewComboBoxCell)ModeCell.Clone();
              dataGridView1[i, 3].Value = "C";
         }
    }
}

我正在尝试使用WPF实现相同的功能。但我无法做到这一点(我无法找到DataGridViewComboBoxCell)。

我该怎么做?

(请帮助一个例子。我是WPF的新手,在绑定方面没有太多想法)。

1 个答案:

答案 0 :(得分:1)

好的,所以我希望你愿意自己做一些工作......你会有很多来做。 WPF 非常与WinForms不同,因此您无法使用WinForms代码作为开始。你将不得不面对一种截然不同的工作方式。在WPF中,我们使用数据元素,而不是 UI元素

我的意思是我们构建的类包含 UI中所需的所有属性实现INotifyPropertyChanged interface 。然后,当我们在UI中声明了这些类的集合时,我们只需将数据绑定到集合控件的ItemsSource属性:

<DataGrid ItemsSource="{Binding YourItems}" />

DataGrid会自动为您生成列。所以要回答你的问题,我们需要做的就是在DataGrid中添加一个新行,就是在代码中将新项添加到集合中:

YourItems.Add(new YourItemClass());

INotifyPropertyChanged界面将负责为您更新UI。所以,这是你基本形式的答案。

我没有尝试在这里教你所有的WPF,我更愿意为你指出一些非常有用的在线资源,让你更好地了解可行的方法和方法:

  来自WPF Tutorial.net的

WPF DataGrid Control
  来自CodeProject的WPF DataGrid Practical Examples