问题
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!
回答1:
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
.
来源:https://stackoverflow.com/questions/16958476/cannot-bind-observablecollection-to-list-dp-from-xaml