2
votes

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

Currently I 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}"/>

Unfortunatly, when I actually run this I get an exception stating:

A 'Binding' cannot be used within a 'TextBox' collection. A 'Binding' can only be set on a 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 this type and getting confused in the process. Anyone know what I need to do to make it work?

1

1 Answers

4
votes

The ownerType in the DependencyProperty.RegisterAttached call is the type that is registering the DependencyProperty. In your example, that isn't 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));