user2975847
user2975847

Reputation: 439

Programmatically set a data-bound combobox at window startup

There are other posts about this, but nothing that fits my situation on programatically setting the selected value.

I have a WPF window that has a combobox and as an input into that window, I have an ID value that corresponds to the values in this data-bound combobox. I've tried several ways to set the combobox.SelectedItem or combobox.SelectedIndex etc and each time, the value doesn't change. Looking deeper, since I'm performing this action from the window constructor after InitializeComponent() is called. Unfortunately, the combobox.Items is not populated, so the Items list has a count of 0. The binding is happening correctly, but obviously somehow it's not hooked up until after the window constructor is completed.

This is the trimmed down xaml for the combobox:

<ComboBox Name="Combobox_cmb" Grid.Column="0" Grid.Row="0"  ItemsSource="{Binding Path=Names}" DisplayMemberPath="Name" SelectedValuePath="Name" SelectionChanged="Name_cmb_SelectionChanged" />

Of course "Names" is an observable list that gets loaded before trying to set the selected value. Even though the back end list is populated, if I look at the Combobox_cmb.Items after populating the list and before setting the selected value, Combobox_cmb.Items is empty.

Is there a way to pass in a value to the window and have a combobox default to that item?

Thanks

Upvotes: 1

Views: 248

Answers (1)

Ninglin
Ninglin

Reputation: 146

Have you tryed doing it in the Window.Loaded event? Try doing this:

public YourWindow()
{
   InitializeComponent();
   this.Loaded += Window_Loaded;
   this.Datacontext = viewmodel // if you'r going with MVVM
}

public void Window_Loaded(object sender, RoutedEventArgs e)
{
   Combobox_cmb.ItemsSource = ((Viewmodel)this.DataContext).Names; //Names should be in your viewmodel if you're going with MVVM. If not just use DataContext as this codebehind and place the list here.
}

Don't know if this helps cause I can't contextualize the answer. Maybe provide a bit more code.

Upvotes: 1

Related Questions