问题
I hope someone can help me or post a link to related question, that would have the answer. I have read most of them and thats how I got this far...
So I have a datagrid with 3 columns, two of them are binded to one datatable and the third one that is a comboboxcolumn should be binded to the other one.
I binded the combobox column to a static resource.
What I don't uderstand how to transform a datatable to a list of keyvalue pairs that I want to use as a static resource for my comboboxcolumn.
public class MyClasificators:List<KeyValuePair<object, object>>
{
public MyClasificators()
{
this.Add(new KeyValuePair<object, object>(1, "Test"));
this.Add(new KeyValuePair<object,object>(2, "Test1"));
this.Add(new KeyValuePair<object, object>(3, "Test2"));
}
}
XAML:
<local:MyClasificators x:Key="clList"></local:MyClasificators>
Combobox column:
<dg:DataGridTemplateColumn Header="test">
<dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{StaticResource clList}" DisplayMemberPath="Value" / >
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
Now this works fine but how do I pass this table to the MyClassificators class and how do I convert it to list> :
DataTable country = new DataTable();
country.Columns.Add(new DataColumn("id_country", typeof(int)));
country.Columns.Add(new DataColumn("name", typeof(string)));
DS.Tables.Add(country);
回答1:
Assuming that "country" is your filled table, that column 0 is "id_country" and column 1 is "name" :
public MyClasificators()
{
//Acquire "country" DataTable before this point
foreach (DataRow row in country.Rows)
{
this.Add(new KeyValuePair<object, object>(row.ItemArray[0], row.ItemArray[1]));
}
}
This will loop through all the rows in the DataTable and get the first two items of each row and add them respectively to the list ;)
来源:https://stackoverflow.com/questions/16622425/wpf-datagrid-combobox-binding-staticresource-list-of-keyvalue-pairs