设置 WPF ComboBox 的 SelectedItem [英] Set SelectedItem of WPF ComboBox

查看:42
本文介绍了设置 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-Tag 如下:

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">

我添加了属性定义 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";

注意值必须是字符串.对于您的示例,请使用

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

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.

这篇关于设置 WPF ComboBox 的 SelectedItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆