从非 DependencyObject 读取附加属性
XAML 允许我将属性附加到不是从 DependencyObject 派生的类型。例如,我可以为窗口上的 CommandBindings 命名:
<Window.CommandBindings>
<CommandBinding x:Name="Refresh" Command="NavigationCommands.Refresh" />
<CommandBinding x:Name="Print" Command="ApplicationCommands.Print" />
</Window.CommandBindings>
我在 MSDN 上发现了这种可能性的提及 (附加属性概述),其中指出“如果您的类严格定义附加属性以用于其他类型,则该类不必从 DependencyObject 派生。但您可以如果您遵循将附加属性也作为依赖属性的整体 WPF 模型,则需要从 DependencyObject 派生。” - 但我不知道如何在代码中获取这些附加属性。
将上述 XAML 代码插入到
中,如何从每个 CommandBinding
检索 x:Name
属性的值?
XAML lets me attach properties to types that are not derived from DependencyObject. For example, I could give names to the CommandBindings on a Window:
<Window.CommandBindings>
<CommandBinding x:Name="Refresh" Command="NavigationCommands.Refresh" />
<CommandBinding x:Name="Print" Command="ApplicationCommands.Print" />
</Window.CommandBindings>
I found mention of this possibility on MSDN (Attached Properties Overview), which states "If your class is defining the attached property strictly for use on other types, then the class does not have to derive from DependencyObject. But you do need to derive from DependencyObject if you follow the overall WPF model of having your attached property also be a dependency property." - but I have no idea how to get at these attached properties in code.
Given the above XAML code inserted into a <Window />
, how can I retrieve values of the x:Name
properties from each CommandBinding
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以倒着读:您不能将附加属性应用于非
DependencyObject
。但是,您可以在不是从DependencyObject
派生的类上定义附加属性。通常是静态类,例如 WPF 中的FocusManager
。x:Name
不是附加属性:它是一个 指令。在FrameworkElement
的常见情况下,它与FrameworkElement.Name
相同。对于自定义类,其目的是定义一个同名的字段(这应该是您的情况:您现在可以从代码中获得Refresh
和Print
字段-在后面)。在每种情况下(除了在ResourceDictionary
内),它都会添加到当前的 XAML 名称范围。您可以在
Window
上使用 FindName从其名称获取命令绑定。如果您确实需要从对象中获取名称,则可以使用以下代码来获取包含范围内每个命名元素的可枚举字典:You read it backwards: you can't apply an attached property to a non-
DependencyObject
. You can however define an attached property on a class not deriving fromDependencyObject
. Typically a static class, likeFocusManager
in WPF.x:Name
is not an attached property: it's a directive. In the common case of aFrameworkElement
, it's the same asFrameworkElement.Name
. In the case of a custom class, its purpose is to define a field of the same name (which should be your case: you now haveRefresh
andPrint
fields available from code-behind). In every case (except inside aResourceDictionary
), it's added to the current XAML namescope.You can use FindName on your
Window
to get a command binding from its name. If you really need to get the name back from the object, you can use the following piece of code to get an enumerable dictionary containing every named element in the scope: