Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...