CBreeze CBreeze - 1 month ago 16
C# Question

Binding a ComboBox

I have an

ObservableCollection
of JobTitles that I want to bind to a ComboBox. Using binding through XAML I've had no luck, so I've ended up doing this;

foreach (PresetModel jobTitle in JobTitles)
{
var _newItem = new ComboBoxItem();
_newItem.Content = jobTitle.Text;
_newItem.Tag = jobTitle.ID;
jobTitleComboBox.Items.Add(_newItem);
}


This actually does add all of the JobTitles to the ComboBox (further than I got with bindig) however now the issue is that when the user selects an Employee, who has a JobTitle, I want to select the relevant JobTitle in the ComboBox.

Ideally I'd do this;

jobTitleComboBox.Text = currentUser.JobTitle;


However this does not work. I only have access the Employees JobTitle text, not the ID of the title which I don't think helps. How can I display the relevant job title for the Employee?

Answer

If you have a collection named: JobsCollection. And on this collection you have JobId, JobName ...etc attributes. Then, on your XAML you could simply write:

ComboBox ItemsSource="{Binding JobsCollection}" DisplayMemberPath="JobName"

So,
DisplayMemberPath -> Which property you want to show on the Combobox list
Binding -> The name of the ObservableCollection you want to bind.

Edit: How XAML Element would look like

<ComboBox ItemsSource="{Binding JobsCollection}" 
          SelectedItem={Binding SelectedItemName} 
          DisplayMemberPath="JobName" />