【问题标题】:WPF Property Binding Source Property not being Accessed未访问 WPF 属性绑定源属性
【发布时间】:2015-01-22 05:03:03
【问题描述】:

我正在尝试将继承自 MenuItem 的控件上的依赖属性绑定到我的窗口的依赖属性。我已经在两个属性的 get 和 sets 上设置了断点,但我从来没有看到被调用的窗口的属性 get。窗口属性为源,控件属性为目标。

控件的属性如下所示:

Public Shared StorageProperty As DependencyProperty = 
                                 DependencyProperty.Register("Storage",
                                                             GetType(IStorage),
                                                             GetType(MRUFileList),
                                                             New PropertyMetadata(Nothing))

Public Property Storage As IStorage
    Get
        Return DirectCast(GetValue(StorageProperty), IStorage)
    End Get
    Set(value As IStorage)
        SetValue(StorageProperty, value)
    End Set
End Property

而窗口的属性是:

Public Shared ReadOnly MRUStorageProperty As DependencyProperty =
                                             DependencyProperty.Register("MRUStorage",
                                                                         GetType(MRU.IStorage),
                                                                         GetType(GrammarEditor),
                                                                         New PropertyMetadata(Nothing))

Public Property MRUStorage As MRU.IStorage
    Get
        Return DirectCast(GetValue(MRUStorageProperty), MRU.IStorage)
    End Get
    Set(value As MRU.IStorage)
        SetValue(MRUStorageProperty, value)
    End Set
End Property

最后,定义绑定的 XAML 是:

<mru:MRUFileList Name="mnuRecent" 
                 Header="Open _Recent" 
                 Storage="{Binding MRUStorage, 
                           Mode=TwoWay, 
                           UpdateSourceTrigger=PropertyChanged}" />

以前我曾尝试将 RelativeSource 设置为 Self 以及 FindAncestor,并将 AncestoryType 设置为 Window。

【问题讨论】:

    标签: .net wpf xaml binding dependency-properties


    【解决方案1】:

    使用依赖属性绑定永远不会调用 get/set,因为绑定是使用依赖属性基础结构解析的。如您所见,您的属性所做的就是让您通过调用

    轻松访问该依赖属性的值
    GetValue(StorageProperty)
    

    绑定引擎直接调用它而不是使用您的属性

    编辑:您的窗口是否具有 MRUStorage 作为属性?您将需要它才能将其用作绑定路径

    【讨论】:

    • 我明白您对所使用的 GetValue 方法而不是属性的意思。这个问题仍然存在,因为当我调用 GetValue 时,它​​似乎没有设置属性,它返回 Nothing。是的,我确实在窗口中有一个属性,我忘记将它包含在我原来的问题中。我现在添加它。
    • 我不确定这个问题,除非您正确设置了 Windows 数据上下文,否则绑定不正确。您将需要 RelativeSource={RelativeSource AncestorType={x:Type Window}} 但您说您已经尝试过了。
    • 我想你刚刚修好了。我之前对 RelativeSource 的尝试是:RelativeSource={RelativeSource AncestorType=Window} 添加 {X:Type Window} 似乎已经解决了这个问题。
    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多