WPF自定义控件:集合类型的DependencyProperty

我有一个包含ListBoxCustomControl

      

我使用Code Behind中的属性绑定ItemsSource

 public partial class CustomList : UserControl, INotifyPropertyChanged { public CustomList( ) { InitializeComponent( ); } public ObservableCollection ListSource { get { return (ObservableCollection)GetValue( ListSourceProperty ); } set { base.SetValue(CustomList.ListSourceProperty, value); NotifyPropertyChanged( "ListSource" ); } } public static DependencyProperty ListSourceProperty = DependencyProperty.Register( "ListSource", typeof( ObservableCollection ), typeof( CustomList ), new PropertyMetadata( OnValueChanged ) ); private static void OnValueChanged( DependencyObject d, DependencyPropertyChangedEventArgs e ) { ( (CustomList)d ).ListSource = (ObservableCollection)e.NewValue; } public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged( string propertyName ) { if(PropertyChanged != null) { PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) ); } } } 

现在在我的MainWindow我尝试使用CustomControl和它的ListSource DependencyProperty绑定一个ObservableCollection “Articles”:

      

我得到的错误:

 Error: 1 : Cannot create default converter to perform 'one-way' conversions between types 'System.Collections.ObjectModel.ObservableCollection`1[WpfApplication1.Article]' and 'System.Collections.ObjectModel.ObservableCollection`1[System.Object]' 

如果在自定义控件中我有ObservableCollection

而不是ObservableCollection它可以工作。 那么有没有办法可以将自定义控件的DependencyProperty与ObservableCollection对象绑定,而无需指定对象的类型?

将ListSource的类型更改为IEnumerable,然后您可以绑定到任何集合。