tags:

views:

36

answers:

3

I have a viewmodel with a property Animals of type list. I am trying to bind this list to a combobox in my xaml page. I cannot seem to get this combobox to bind. What am I doing wrong?

<ComboBox x:Name="uxAnimal" Grid.Row="0" Grid.Column="1" Width="130" HorizontalAlignment="Left"  ItemsSource="{Binding Path=Animals}"  >

Thanks

A: 

Perhaps you need to convert your List (if that is the data type you are using) into an ObservableCollection. Like this:

ObservableCollection<Animal> newList = new ObservableCollection<Animal>(oldList);

Where "oldList" is your original list of type List.

Chazmanian
I've actually tried this, but to no avail. Animal really is just a List<String>.
silverlightquest
A: 

Presumable your combo box is getting bound before Animals is populated, and since Animals is not an ObservableCollection it has no way to tell the combo box that it's contents have changed...

Two easy options:

  1. Assuming the class that contains Animals implements INotifyPropertyChanged you just need to raise a PropertyChanged event AFTER you populate Animals with values.

  2. Do your binding from code instead of in xaml. After Animals is populated with data you could:

    uxAnimal.ItemsSource = Animals;

Scrappydog
Thanks for your answers. It turned out that my datacontext was incorrectly set.
silverlightquest
A: 

You don't need put your list items into an ObservableCollection actually but on the model you should have it implement INotifyPropertyChanged and fire the property when you set the list.

private IList _myList;
public IList Animals 
{
    get { return _myList; }
    set { 
         _myList = value; 
          if (PropertyChanged != null) { 
                PropertyChanged(this, new PropertyChangedEventArgs("Animals"); 
            } 
        }
}

BTW, you can use the nice System.Windows.Data.CollectionViewSource to get an ICollectionView to have notifications, current item tracking etc. for free from you list.

R4cOON