简体   繁体   中英

WPF Bind Dictionary to combobox

I have the List of double Arrays. Some values are predefined. And I want to bind this list to DataGrid. Actually datagrid cells are comboboxes filled with Dictionary Values. The idea is that user selects any value from dropdown and appropriate Key is written to List with double Arrays. Code is the following:

        Dictionary<int, string> scores = new Dictionary<int, string>();                                   
        scores.Add(1, "the same");
        scores.Add(3, "moderate superiority");
        scores.Add(5, "strong superiority");
        scores.Add(7, "very strong superiority");
        scores.Add(9, "extremely superiority");


        //define number of alternatives
        int num = Alternatives.Children.Count - 1;

        //initialize matrix for assessment scores
        List<double[]> gridAssessment = new List<double[]>();
        for (int i = 0; i < num; i++)
        {                
            gridAssessment.Add(new double[num]);
        }

        //set initial values
        for (int i = 0; i < num; i++)
        {
            gridAssessment[i][i] = scores.ElementAt(0).Key;                
        }

        //define source for assessment grid
        grAssessment.ItemsSource = gridAssessment;
        grAssessment.AutoGenerateColumns = false;            


        //add columns to the grid
        for (int i = 0; i < num; i++)
        {
            DataGridComboBoxColumn col = new DataGridComboBoxColumn();               
            grAssessment.Columns.Add(col);
            col.Width = new DataGridLength(1, DataGridLengthUnitType.Star);

            //define source for comboboxes
            col.ItemsSource = scores;                
            col.DisplayMemberPath = "Value";
            col.SelectedValuePath = "Key";
            string a = "[" + i.ToString() + "]";
            Binding t = new Binding(a);
            t.Mode = BindingMode.TwoWay;                
            col.SelectedValueBinding = t;  

Actually when I select any value from dropdown validation mark appears. Could you please assist me with this binding?

Thanks a lot.

The issue resides here:

//initialize matrix for assessment scores
List<double[]> gridAssessment = new List<double[]>();
for (int i = 0; i < num; i++)
{
    gridAssessment.Add(new double[num]);
}

Checking the Output window, it says it "cannot convert back". So when it tries to convert a double back to an int, it has a problem. If you change this to int to match the "scores" data type, the validation will be gone.

Fixed Code:

//initialize matrix for assessment scores
List<int[]> gridAssessment = new List<int[]>();
for (int i = 0; i < num; i++)
{
    gridAssessment.Add(new int[num]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM