无法将ObservableCollection绑定到来自xaml的List dp

时间:2013-06-06 09:29:10

标签: wpf xaml data-binding dependency-properties

我有一个名为Switch的userControl,它有一个List类型的DependancyProperty,名为ImageList。 在我的ViewModel中,我创建了一个名为imgList的ObservableCollection。 在My XAML窗口中,我写了以下行:

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

最令我遗憾的是,这根本不起作用,而且ImageList没有收到请求的值。

ImageList定义如下:

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); }
}

viewModel是正确的,如下所示:

<ComboBox ItemsSource={Binding imgList}/>

有趣的是,这可以正常工作:

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

提前致谢!

1 个答案:

答案 0 :(得分:2)

您如何期望ObservableCollection<>类型(imgList)的传入值与List<>类型(Switch.ImageList)匹配?

请使您的类型兼容。

一种方法是将ImageListProperty重新声明为IList<>类型为ObservableCollection<>实现IList接口。

在WPF中,当目标属性的类型相同或者源类型的基本类型时,将使用绑定。 ObservableCollection并非来自List<>

修改

您的上一个示例停止工作,因为IList<>没有隐式实例化(作为接口),没有通过XAML提供给它的显式集合类型。将ImageListProperty更改为IList(不是IList<T>)。

你应该改变这种方式......

 <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>

这是有效的,因为ArrayList是一个实现IList的具体XAML序列化集合。 ObservableCollection<>也可以IList