Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

wpf datagrid combobox binding staticresource list of keyvalue pairs

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...