我有一個CustomControl
含有ListBox
:WPF自定義控件:集合類型的DependencyProperty
<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
在後面的代碼屬性:在我MainWindow
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));
}
}
}
現在我嘗試將「Articles」的ObservableCollection
與我的CustomControl
及其ListSource DependencyProperty綁定:
<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對象綁定,而無需指定對象的類型?
您並不需要(實際上不應該)在DependencyProperties上實現INotifyPropertyChanged,也不要**將任何代碼放置在依賴項proeprty的setter中。 – 2011-04-14 13:52:25
@ H.B。你是說依賴項屬性會自動實現適當的更改通知?或者,你是否建議有更好的選擇? – Rachael 2013-04-17 21:33:44
@ UB3571:是的,他們確實實施了更改通知,但它們引入了線程關聯。正如我所說的,另一種方法是'INotifyPropertyChanged'。 – 2013-04-18 02:30:14