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?
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, likeFocusManagerin WPF.x:Nameis 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 haveRefreshandPrintfields available from code-behind). In every case (except inside aResourceDictionary), it’s added to the current XAML namescope.You can use FindName on your
Windowto 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: