Maya
Maya

Reputation: 1009

Cannot bind ObservableCollection to List dp from xaml

I have a userControl named Switch which has a DependancyProperty of type List, named ImageList. In my ViewModel, I create a ObservableCollection named imgList. In My XAML window, I write the following line:

<loc:switch ImageList={Binding imgList}/>

To my greatest regret, this does not work at all and ImageList does not recieve the requested values.

ImageList is defined as the following:

public static readonly DependancyProperty ImageListProperty = DependancyProperty.Register
  ("ImageList", typeof(List<ImageSource>), typeof(Switch));

public List<ImageSource> ImageList {
  get { return (List<ImageSource>)GetValue(ImageListProperty); }
  set { SetValue(ImageListProperty, value); }
}

The viewModel is correct, as the following works:

<ComboBox ItemsSource={Binding imgList}/>

It is interesting to note that this works correctly:

<loc:switch>
  <loc:switch.ImageList>
    <BitmapImage UriSource="Bla.png"/>
    <BitmapImage UriSource="Bla2.png"/>
  </loc:switch.ImageList>
</loc:switch>

Thanks in advance!

Upvotes: 0

Views: 345

Answers (1)

Vinit Sankhe
Vinit Sankhe

Reputation: 19885

How do you expect an incoming value of ObservableCollection<> type (imgList) would match with List<> type (Switch.ImageList)?

Please make your types compatible.

One way is to redeclare ImageListProperty to IList<> type as ObservableCollection<> implements IList interface.

In WPF Binding would wouk when the target property's type is same or a base type to the source value. ObservableCollection doesnt derive from List<>.

EDIT

Your last example stops working because IList<> isnt instantiated implicitly (being an Interface) without explicit collection type supplied to it via XAML. Change ImageListProperty to IList (Not IList<T>).

You should it change this way....

 <loc:switch xmlns:coll="clr-namespace:System.Collections;assembly=mscorlib">
   <loc:switch.ImageList>
     <coll:ArrayList>
         <BitmapImage UriSource="Bla.png"/>
         <BitmapImage UriSource="Bla2.png"/>
     </coll:ArrayList>
   </loc:switch.ImageList>
 </loc:switch>

This works because ArrayList is a concrete XAML serialized collection that implements IList. And ObservableCollection<> also does plain IList.

Upvotes: 2

Related Questions