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

查看:1343
本文介绍了设置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.

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

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