Binding to an ObservableCollection attached property.

Posted by bwreichle on Stack Overflow See other posts from Stack Overflow or by bwreichle
Published on 2010-05-02T00:43:14Z Indexed on 2010/05/02 0:47 UTC
Read the original article Hit count: 740

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf