【问题标题】:Binding to an ObservableCollection attached property绑定到 ObservableCollection 附加属性
【发布时间】:2011-02-14 16:12:35
【问题描述】:

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

目前我有:

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

不幸的是,当我实际运行它时,我得到一个异常说明:

“绑定”不能在“文本框”集合中使用。 “绑定”只能在 DependencyObject 的 DependencyProperty 上设置。

这似乎只是在附加属性的类型为 ObservableCollection 时才会出现问题,因此 WPF 在绑定这种类型的属性时似乎正在尝试做一些神奇的事情,并在此过程中感到困惑。任何人都知道我需要做什么才能使其工作?

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

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

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

    【讨论】:

    • 我认为所有者是您想要将属性应用到的依赖对象的类型:)。谢谢,您的解决方案效果很好。
    猜你喜欢
    • 1970-01-01
    • 2011-02-07
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    相关资源
    最近更新 更多