Binding Custom Objects to Combobox in WPF
I have been struggling with trying to bind an IList<T> that holds custom objects to my combobox in WPF. I am implementing the MVP Design Pattern and have a WPF User Control as a container for other User Controls that I create during runtime. I set a property in the parent container presenter to hold my IList<T> of objects. I then created my custom controls in the parent container presenter and then created a function to set the properties of the combobox for the data binding. So far it looked like so:
Property to hold custom objects
private IList<CustomObjects> _customObjectsList;
public IList<CustomObjects> CustomObjectsList
{
get
{
return _customObjectsList;
}
set
{
_customObjectsList = value;
}
}
User action to create new controls
public void ClickedAddButton(Object sender, EventArgs e)
{
ChildUserControlView newChildUserControlView = new ChildUserControlView ();
ParentContainer.Children.Add(newChildUserControlView );
ParentContainer.UpdateLayout();
newChildUserControlView .Focus();
BindCombobox(newChildUserControlView );
}
private void BindCombobox(ChildUserControlView pvv)
{
pvv.Combobox.ItemsSource = _customObjectsList;
pvv.Combobox.DisplayMemberPath = “ShortName”;
pvv.Combobox.SelectedValuePath = “Id”;
pvv.Combobox.SelectedIndex = 0;
}
I then ran the program and all was working well except that I could not ever get the combobox to show the “ShortName” property value in the combobox when selected. It was always the <objectname>.ToSting().
Everything I had read up to that point seemed to say that I was binding correctly. i even attempted to create resoucres in the Xaml and even went as far as creating the bindings from scratch in code. Still no luck. I then ran across this article http://msdn2.microsoft.com/en-us/library/aa480226…. that pointed me to DataTemplates. I decided to give it a try. I created a simple template as seen in the article. I then modified my BindCombobox method like so:
private void BindCombobox(ChildUserControlView pvv)
{
pvv.ComboBox.DataContext = _customObjectsList;
}
Now all is working well. Please read the attached article as I am not going to rehash it, but by setting the DataContext and using a DataTemplate. I was up and going. I am not sure why this did not work out the way I had started and I even posted to the MSDN forums with no real answer. So I have now discovered that there might be something really cool about these DataTemplates and I have a better understanding of them. Growth through adversity :-).
-paul