设置WPF ComboBox的SelectedItem

设置WPF ComboBox的SelectedItem

问题描述:

<ComboBox Grid.Row="1" Grid.Column="0" Width="Auto" Name="cmbBudgetYear">
   <ComboBoxItem Content="2009" />
   <ComboBoxItem Content="2010" />
   <ComboBoxItem Content="2011" />
   <ComboBoxItem Content="2012" />
</ComboBox>

如何将所选项目设置为代码中的当前年份?

How do I set the selected item to the current year in the code behind?

有点像...

cmbBudgetYear.SelectedItem = cmbBudgetYear.Items(
                                         get the item with the Now.Year.ToString)


有很多方法可以做到这一点,但在你的例子中,我将更改ComboBox标签如下:

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

<ComboBox Grid.Row="1" Grid.Column="0" 
          Name="cmbBudgetYear" SelectedValuePath="Content">

我添加了attribute-defition SelectedValuePath =Content。之后,您可以使用相应的字符串设置值,例如:

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

cmbBudgetYear.SelectedValue = "2009";

注意值必须是字符串。例如,使用

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

另一个想法

如果你使用代码隐藏,是否有可能用整数填充组合框。类似:

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.