2010-05-02 100 views
2

我想创建一个类型为ObservableCollection的附加属性<通知>并将其绑定到DataContext上的同一类型的属性。绑定到ObservableCollection附加属性

目前我有:

internal static class Squiggle 
{ 
    public static readonly DependencyProperty NotificationsProperty = DependencyProperty.RegisterAttached(
     "Notifications", 
     typeof(ObservableCollection<Notification>), 
     typeof(TextBox), 
     new FrameworkPropertyMetadata(null, NotificationsPropertyChanged, CoerceNotificationsPropertyValue)); 

    public static void SetNotifications(TextBox textBox, ObservableCollection<Notification> value) 
    { 
     textBox.SetValue(NotificationsProperty, value); 
    } 

    public static ObservableCollection<Notification> GetNotifications(TextBox textBox) 
    { 
     return (ObservableCollection<Notification>)textBox.GetValue(NotificationsProperty); 
    } 

    ... 
} 

用下面的XAML:

<TextBox 
    x:Name="configTextBox" 
    Text="{Binding Path=ConfigText, UpdateSourceTrigger=PropertyChanged}" 
    AcceptsReturn="True" 
    AcceptsTab="True" 
    local:Squiggle.Notifications="{Binding Path=Notifications}"/> 

不幸的是,当我真正运行此我得到一个异常说明:

A '绑定'不能在'TextBox'集合中使用。 '绑定'只能在DependencyObject的DependencyProperty上设置。

这似乎只所以它看起来像WPF试图结合这种类型的属性时,并在过程中感到困惑做一些神奇的是,当附加属性的类型的ObservableCollection的问题。任何人都知道我需要做些什么才能使它工作?

回答

4

DependencyProperty.RegisterAttached调用中的ownerType是注册DependencyProperty的类型。在你的例子中,那不是TextBox,它的Squiggle。所以你想要的代码是:

public static readonly DependencyProperty NotificationsProperty = DependencyProperty.RegisterAttached(
    "Notifications", 
    typeof(ObservableCollection<Notification>), 
    typeof(Squiggle), 
    new FrameworkPropertyMetadata(null, NotificationsPropertyChanged, CoerceNotificationsPropertyValue)); 
+0

而且我认为所有者是你想将属性应用到的依赖对象的类型:)。谢谢,你的解决方案完美无缺。 – 2010-05-02 06:52:26