Binding to ObservableCollection object

I want to create an attached property of type ObservableCollection <Notification> and bind it to a property of the same type in the DataContext.

I currently have:

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);
    }

    ...
}

      

With the following XAML:

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

      

Unfortunately, when I actually run this, I get an exception:

"Binding" cannot be used on the "TextBox" collection. "Binding" can only be set on the DependencyProperty of a DependencyObject.

This only seems to be a problem when the attached property is of type ObservableCollection, so it seems like WPF is trying to do something magical when binding properties of that type and getting confused in the process. Does anyone know what I need to do to make it work?

+2


a source to share


1 answer


OwnerType in Call DependencyProperty.RegisterAttached is the type that registers the DependencyProperty . In your example, this is not TextBox

, its Squiggle

. So the code you want is:



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

      

+4


a source







All Articles