问题
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