Reading Attached Property from Non-DependencyObject

大憨熊 提交于 2019-12-11 02:49:41

问题


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?


回答1:


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 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.

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


来源:https://stackoverflow.com/questions/6483515/reading-attached-property-from-non-dependencyobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!