RoutedUICommand的ownerType参数作用、传参及取值疑问咨询
Let's break down each of your questions about the ownerType parameter in RoutedUICommand clearly, based on WPF's command system behavior:
1. What is the purpose of the ownerType parameter?
The ownerType serves two core functions:
- Command Binding Resolution: When a command is triggered, WPF scans the visual tree for matching
CommandBindinginstances. TheownerTypeacts as a filter—only bindings linked to the specified type (or its derived types) will be considered. This prevents conflicts between commands that share the same name but belong to different parts of your application. - Localization & Resource Lookup: If you use localized string resources for your command's text, WPF uses
ownerTypeto locate the correct resource entries associated with that type.
Put simply, it gives your command a distinct identity tied to a specific type, guiding how WPF interacts with and resolves it.
2. Is passing null or typeof(object) as ownerType feasible?
Both are technically allowed, but they come with tradeoffs:
- Passing null: The command won't be linked to any specific owner type. When resolving bindings, WPF will match any
CommandBindingwith the same command name/gesture, regardless of the binding's owner. This can lead to unintended bindings if another command with the same name exists elsewhere in your app. - Passing typeof(object): Since every .NET type inherits from
object, this behaves almost identically to passing null. WPF won't filter bindings by owner type here, as all types qualify underobject.
While these work, it's better practice to use a specific owner type (like your CustomApplicationCommands class) to keep your command's identity clear and avoid accidental conflicts.
3. What is the ownerType value when using the parameterless constructor?
When you call the empty RoutedUICommand() constructor, the ownerType is set to null by default. This means the command has no associated owner type, just like explicitly passing null to the parameterized constructor.
Quick Note on Your Code Example
In your current code, you're using typeof(object) as the ownerType. A cleaner, more intentional approach would be to link it directly to your static class:
public static RoutedUICommand SettingsCommand = new RoutedUICommand( text: "Opens the settings window", name: nameof(SettingsCommand), ownerType: typeof(CustomApplicationCommands), inputGestures: new InputGestureCollection(new InputGesture[] { new KeyGesture(Key.F10) }) );
This explicitly ties the command to your CustomApplicationCommands type, making its purpose and identity unambiguous.
内容的提问来源于stack exchange,提问作者ˈvɔlə

