Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

Set SelectedItem of WPF ComboBox

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

Something like...

cmbBudgetYear.SelectedItem = cmbBudgetYear.Items(
                                         get the item with the Now.Year.ToString)
question from:https://stackoverflow.com/questions/3391195/set-selecteditem-of-wpf-combobox

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...