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

How to programmatically form an observable collection and bind it to a datagrid

我有一个问题,我将分为两个步骤:

问题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;

问题是绑定结果如下图:


问题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; }
}

结果是:

将您的 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);

来自

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);