Command instantiation and lifecycle
im new to wpf and commands and would like s开发者_StackOverflow社区ome instrumental advice relating to when / how are custom command classes instantiated:
Should _canExecute be static or not?
public class ExitCommand : ICommand
{
static bool _canExecute = true;
public bool CanExecute(object parameter)
{
return _canExecute;
}
...
}
ExitCommand is Part of App Resource Dictionary
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source=".....
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
ExitCommand is Located as StaticResource
<MenuItem Header="Exit" Command="{StaticResource ExitCommand}"/>
If I want to control CanExecute with _canExecute will its value survive if I declare the Boolean non-statically? Or in other words, when is ExitCommand instantiated:
Is it instantiated only once per application session whenever the application resources are loaded?
Is ExitCommand instantiated every time the command is triggered by e.g. clicking on the Exit menu item?
I can not see any instantiation in your XAML snippet, but if you declare it directly in the Application.Resources
(without setting x:Shared
to false
) there will normally only be one instance accross the whole application, but this cannot be guaranteed as we are dealing with a dictionary, so you could always swap out the instance found using that specific key.
This being the case there is no real need to make the field static (if you suspect tampering with the dictionary you might want to though), if anything i would create the command statically and readonly in a static class where it can be accessed easily (using x:Static
in XAML and a normal access path in code behind).
Also there are already ApplicationCommands
, which could be used instead of your custom command. And you could also add your own to the App
class itself which then can be bound to using {Binding ExitCommand, Source={x:Static local:App.Current}}
, might be a bit more verbose but the command is closer to where it belongs and you also certainly have the right instance.
精彩评论