[英]WPF Custom Control: DependencyProperty of Collection type
我有一個包含ListBox
的CustomControl
:
<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>
我使用Code Behind中的屬性綁定ItemsSource
:
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
我嘗試使用CustomControl
和它的ListSource DependencyProperty綁定一個ObservableCollection
“Articles”:
<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綁定,而無需指定對象的類型?
將ListSource的類型更改為IEnumerable,然后您可以綁定到任何集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.