如何以编程方式形成可观察集合并将其绑定到数据网格

时间:2016-02-11 12:37:52

标签: c# wpf data-binding datagrid observablecollection

我有一个问题,我分两步:

问题1。

形成一个可观察的字符串集合并将其绑定到数据网格

ObservableCollection<string[]> octest = new ObservableCollection<string[]>();
var el = new string[6] {"1","2","3", "4", "5", "6" };
octest.Add(el);
octest.Add(el);
octest.Add(el);
dtgResults.ItemsSource = octest;

问题是绑定结果如下图所示:

enter image description here

问题2

相同但现在有一个字符串数组但有混合元素(例如3个字符串和3个双打)

谢谢

- 编辑 - 用于CBreeze

我做到了:

  ObservableCollection<TestModel> t = new ObservableCollection<TestModel>();
  var t1 = new TestModel();
  t.Add(t1);
  t.Add(t1);
  t.Add(t1);
  dtgResults.ItemsSource = t;
 }
}

public class TestModel
{
  public TestModel()
  {
    TestDouble1 = new string[3];
    TestDouble1[0] = "A";
    TestDouble1[1] = "B";
    TestDouble1[2] = "C";
  }
  public string[] TestDouble1 { get; set; }
}

结果是:

enter image description here

2 个答案:

答案 0 :(得分:1)

来自

  

programmatically add column & rows to WPF Datagrid

你可以这样做:

string[] columnLabels = new string[] { "Column 0", "Column 1", "Column 2", "Column 3", "Column 4", "Column 5" };

foreach (string label in columnLabels)
{
 DataGridTextColumn column = new DataGridTextColumn();
 column.Header = label;
 column.Binding = new Binding(label.Replace(' ', '_'));

 dtgResults.Columns.Add(column);
}

int[] ivalues = new int[] { 0, 1, 2, 3 };
string[] svalues = new string[] { "A", "B", "C", "D" };

dynamic row = new ExpandoObject();

for (int i = 0; i < 6; i++)
{

 switch (i)
 {
  case 0:
  case 1:
  case 2:
   string str = columnLabels[i].Replace(' ', '_');
   ((IDictionary<String, Object>)row)[str] = ivalues[i];
   break;

   case 3:
   case 4:
   case 5:
    string str2 = columnLabels[i].Replace(' ', '_');
    ((IDictionary<String, Object>)row)[str2] = svalues[i - 3];
    break;

 }
}

dtgResults.Items.Add(row);

答案 1 :(得分:0)

ObservableCollection绑定到Model;

ObservableCollection<TestModel> octest = new ObservableCollection<TestModel>();

创建您的TestModel;

public class TestModel
{
    public double TestDouble1 { get; set; }
    public double TestDouble2 { get; set; }
    public double TestDouble3 { get; set; }
    public string TestString1 { get; set; }
    public string TestString2 { get; set; }
    public string TestString3 { get; set; }
}

然后,您需要实际创建TestModel ....

TestModel newTestModel = new TestModel();

将新值添加到TestModel .....

newTestModel.TestString1 = "Hello"
newTestModel.TestString2 = "Hello"
newTestModel.TestString3 = "Hello"

最后将新TestModel添加到ObservableCollection;

octest.Add(newTestModel);