我有一个CustomControl
,其中包含一个ListBox
:
<UserControl x:Class="WpfApplication1.CustomList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ListBox Name="listBox1" ItemsSource="{Binding ListSource}" />
</Grid>
</UserControl>
我将
ItemsSource
与背后的代码中的属性绑定(bind):public partial class CustomList : UserControl, INotifyPropertyChanged
{
public CustomList( )
{
InitializeComponent( );
}
public ObservableCollection<object> ListSource
{
get
{
return (ObservableCollection<object>)GetValue( ListSourceProperty );
}
set
{
base.SetValue(CustomList.ListSourceProperty, value);
NotifyPropertyChanged( "ListSource" );
}
}
public static DependencyProperty ListSourceProperty = DependencyProperty.Register(
"ListSource",
typeof( ObservableCollection<object> ),
typeof( CustomList ),
new PropertyMetadata( OnValueChanged ) );
private static void OnValueChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
( (CustomList)d ).ListSource = (ObservableCollection<object>)e.NewValue;
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged( string propertyName )
{
if(PropertyChanged != null)
{
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
}
}
现在,在我的
MainWindow
中,我尝试将ObservableCollection
的“Articles”与我的CustomControl
及其ListSource DependencyProperty绑定(bind):<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:CustomList ListSource="{Binding Articles}"/>
</Grid>
</Window>
我得到的错误是:
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<Article>
而不是ObservableCollection<object>
,则可以使用。因此,有没有一种方法可以将我的自定义控件的DependencyProperty与对象的ObservableCollection绑定(bind),而不必指定对象的类型?
最佳答案
将ListSource的类型更改为IEnumerable,然后可以绑定(bind)到任何集合。
关于c# - WPF自定义控件: DependencyProperty of Collection type,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5664091/