Set SelectedItem of WPF ComboBox

后端 未结 4 1390
遇见更好的自我
遇见更好的自我 2020-12-09 07:30

   
   

        
4条回答
  •  一生所求
    2020-12-09 08:21

    There exist many ways to do this but for your example, I would change the ComboBox-Tag as follows:

    
    

    I added the attribute-defition SelectedValuePath="Content". After that you can set the value with a corresponding string, e.g.:

    cmbBudgetYear.SelectedValue = "2009";
    

    Take care that the value must be a string. For your example, use

    cmbBudgetYear.SelectedValue = DateTime.Now.Year.ToString();
    

    An additional idea

    If you use the code-behind anyway, would it be a possibility to fill the combobox with integers. Someting like:

    for(int y=DateTime.Now.Year;y>DateTime.Now.Year-10;y--){
     cmbBudgetYear.Items.Add(y);
    }
    

    ..then you can select the values extremly simple like

    cmbBudgetYear.SelectedValue = 2009;
    

    ... and you would have also other advantages.

提交回复
热议问题