【问题标题】:Cannot bind ObservableCollection to List dp from xaml无法从 xaml 将 ObservableCollection 绑定到 List dp
【发布时间】:2013-06-06 09:29:10
【问题描述】:

我有一个名为 Switch 的 userControl,它有一个 List 类型的 DependancyProperty,名为 ImageList。 在我的 ViewModel 中,我创建了一个名为 imgList 的 ObservableCollection。 在我的 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>

提前致谢!

【问题讨论】:

  • 在你的用户控件中显示绑定和你的依赖属性代码
  • @blindmeis:刚刚添加,谢谢
  • @DHN:这有什么意义?重要的一点是 ImageList 保持不变并且没有得到 VM 中定义的集合

标签: wpf xaml data-binding dependency-properties


【解决方案1】:

您如何期望 ObservableCollection&lt;&gt; 类型 (imgList) 的传入值与 List&lt;&gt; 类型 (Switch.ImageList) 匹配?

请使您的类型兼容。

一种方法是将ImageListProperty 重新声明为IList&lt;&gt; 类型,因为ObservableCollection&lt;&gt; 实现了IList 接口。

在 WPF 中,当目标属性的类型与源值的类型相同或基类型相同时,绑定会出错。 ObservableCollection 不是从 List&lt;&gt; 派生的。

编辑

您的最后一个示例停止工作,因为 IList&lt;&gt; 没有隐式实例化(作为接口),没有通过 XAML 提供显式集合类型。将ImageListProperty 更改为IList(不是IList&lt;T&gt;)。

你应该这样改变....

 <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 是一个具体的XAML 序列化集合,它实现了IList。而ObservableCollection&lt;&gt; 也可以做普通的IList

【讨论】:

  • 这听起来是个好主意。问题是,我之前带来的示例停止工作: 我收到的错误是 IList 只能得到一个孩子
  • 非常感谢你,你是我的救命恩人!
  • 我有一个后续问题:stackoverflow.com/questions/17007491/…你能查一下吗?谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
  • 2018-05-10
  • 1970-01-01
相关资源
最近更新 更多