问题
I have a problem which i'd divide in two steps:
Problem1.
Form an observable collection of strings and bind it to a datagrid
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;
the problem is that the binding results in the image below:
Problem 2
The same but now with an array of strings but with mixed elements (e.g. 3 strings and 3 doubles)
thank you
--EDIT-- for CBreeze
I have done that:
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; }
}
and the result is:
回答1:
from
programmatically add column & rows to WPF Datagrid
you can do that:
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);
回答2:
Bind your ObservableCollection
to a Model
;
ObservableCollection<TestModel> octest = new ObservableCollection<TestModel>();
Create your 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; }
}
You then need to actually create a TestModel
....
TestModel newTestModel = new TestModel();
Add new values to TestModel
.....
newTestModel.TestString1 = "Hello"
newTestModel.TestString2 = "Hello"
newTestModel.TestString3 = "Hello"
Finally add the new TestModel
to the ObservableCollection
;
octest.Add(newTestModel);
来源:https://stackoverflow.com/questions/35339551/how-to-programmatically-form-an-observable-collection-and-bind-it-to-a-datagrid