How to programmatically set SelectedItem of a data-bound WPF ComboBox?
-
Tuesday, August 17, 2010 8:48 AM
Question: Can anyone please provide a full code example that shows how one does programmatically change the SelectedItem of a data-bound WPF ComboBox?
Code sample: Here is what I currently have.
<Window x:Class="Wpf.ComboBoxDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ComboBox Name="MyComboBox" DisplayMemberPath="LastName" SelectedIndex="0"/> </Grid> </Window>using System.Collections.ObjectModel; using System.Windows; namespace Wpf.ComboBoxDemo { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); ObservableCollection<Person> myPersonList = new ObservableCollection<Person>(); Person personJobs = new Person("Steve", "Jobs"); Person personGates = new Person("Bill", "Gates"); myPersonList.Add(personJobs); myPersonList.Add(personGates); MyComboBox.ItemsSource = myPersonList; // How do I programmatically select the second Person, i.e. "Gates"? // The best pratice must be to somehow to set something like IsCurrentlySelected on the model, so the view update automatically. But how? MyComboBox.SelectedIndex = 1; // This works, but is there no way without using the index? } private class Person { public string FirstName { get; set; } public string LastName { get; set; } public Person(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } } } }
Similar questions: I have of course searched the Internet first, but found nothing that helped me.
- Changing the SelectedItem of a enum-bound combobox inside ViewModel (MSDN )
- Programmatically set ComboBox SelectedItem in WPF (3.5sp1) (Stack Overflow )
- Edited by stgn Tuesday, August 17, 2010 9:38 AM
All Replies
-
Tuesday, August 17, 2010 9:16 AM
I'm not sure, I fully understand your question. Are you wanting to set the default item in your list programattically? Here is how I populate a combo box from a SQL Database, and the default selected item is set with this line: "btnServer.SelectedIndex = 3;"
private void SetUpbtnServer() { DataTable dt = bl.GetServerNames(); btnServer.DataContext = dt.DefaultView; Binding bind = new Binding(); Binding tip = new Binding(dt.Columns["ToolTip"].ToString()); btnServer.SelectedIndex = 3; btnServer.IsSynchronizedWithCurrentItem = true; btnServer.Text = "Database Server"; btnServer.ToolTip = "Select the new DB Server."; btnServer.IsTextSearchEnabled = false; btnServer.VerticalAlignment = VerticalAlignment.Top; btnServer.HorizontalAlignment = HorizontalAlignment.Left; btnServer.HorizontalContentAlignment = HorizontalAlignment.Left; btnServer.DisplayMemberPath = dt.Columns["ServerName"].ToString(); btnServer.SetBinding(ComboBoxItem.ToolTipProperty, tip); btnServer.SetBinding(ComboBox.ItemsSourceProperty, bind); } -
Tuesday, August 17, 2010 9:23 AM
SelectedIndex is working for me, too. But SelectedItem = personGates is not working and I don't know why.
I would prefer the SelectedItem approach because otherwise I have to do the following which is rather procedural code, instead of declarative WPF code.
- Find out what person is currently selected in my data model.
- Take the person object and iterate over the items of the combobox to find out its index.
- Set myCombobox.SelectedIndex = indexOfPerson.
Does that clarify my initial question?
- Edited by stgn Tuesday, August 17, 2010 9:28 AM Renamed billGatesInstance to personGates.
-
Tuesday, August 17, 2010 10:39 AM
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace WpfApplication2 { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); ObservableCollection<Person> myPersonList = new ObservableCollection<Person>(); Person personJobs = new Person("Steve", "Jobs"); Person personGates = new Person("Bill", "Gates"); myPersonList.Add(personJobs); myPersonList.Add(personGates); MyComboBox.ItemsSource = myPersonList; MyComboBox.SelectedItem = personGates; } } public class Person { public string FirstName { get; set; } public string LastName { get; set; } public Person(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } } }
This code works fine for me:
Please mark the post as answer if it is helpfull to you because it boosts the members to answer more and more. -
Tuesday, August 17, 2010 11:01 AM
Darn... now it's working here too. *puzzled*
Thank you very much for verifying it!
-
Tuesday, August 17, 2010 11:37 AMEg: when binding to a list to a combobox. In the code-behind you need one line:
combobox.ItemsSource = IList;
and in the xamle you need one line:
<ComboBox Name="Mycombobox" SelectedValue="{Binding Path="This object(int,string,whatever you want) will hold the selected value you specify in the selectedvaluepath property of the combobox", Mode=TwoWay} SelectedValuePath="the ITEM property you want to output from selectedValue" DisplayMemberPath="Name" />
This is the shortest way!

