开发者

Binding to an ObservableCollection attached property

开发者 https://www.devze.com 2022-12-28 16:30 出处:网络
I want to create an attached property of type ObservableCollection<Notification> and bind it to a property of the same type on the DataContext.

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 t开发者_开发问答extBox)
    {
        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?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号