开发者

Binding a combobox to a list in the viewmodel

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 see开发者_开发知识库m 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


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.


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜