从Non-DependencyObject读取附加属性 [英] Reading Attached Property from Non-DependencyObject

查看:66
本文介绍了从Non-DependencyObject读取附加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

XAML使我可以将属性附加到不是从DependencyObject派生的类型。例如,我可以给窗口上的CommandBindings命名:

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>

我在MSDN上提到了这种可能性(附加属性概述),其中指出 如果您的类正在严格定义用于其他类型的附加属性,则该类不必从DependencyObject派生。但是,如果您遵循将附加属性也作为依赖项属性的整体WPF模型,则需要从DependencyObject派生。-但我不知道如何获取

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.

鉴于上面的XAML代码已插入< Window /> 中,如何从每个 CommandBinding 中检索 x:Name 属性的值?

Given the above XAML code inserted into a <Window />, how can I retrieve values of the x:Name properties from each CommandBinding?

推荐答案

您向后阅读:您不能将附加属性应用于非 DependencyObject 。但是,您可以在不是从 DependencyObject 派生的类上定义一个附加属性。通常是静态类,例如WPF中的 FocusManager

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 from DependencyObject. Typically a static class, like FocusManager in WPF.

x:Name 不是附加属性:它是指令。在 FrameworkElement 的常见情况下,它与 FrameworkElement.Name 相同。对于自定义类,其目的是定义一个具有相同名称的字段(应该是您的情况:您现在具有 Refresh 打印字段(可从代码隐藏处获得)。在每种情况下(除了 ResourceDictionary 内),都将其添加到当前的 XAML名称范围

x:Name is not an attached property: it's a directive. In the common case of a FrameworkElement, it's the same as FrameworkElement.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 have Refresh and Print fields available from code-behind). In every case (except inside a ResourceDictionary), it's added to the current XAML namescope.

您可以使用查找名称在您的 Window 上,以从其名称获取命令绑定。如果确实需要从对象中获取名称,则可以使用以下代码段获取包含范围内每个命名元素的可枚举字典:

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:

var dictionary = (INameScopeDictionary) NameScope.GetNameScope(yourWindow);

这篇关于从Non-DependencyObject读取附加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆