I have an WPF application which can take command line parameter. I want to use this command line parameter in ViewModel, I have following options to do that.
1) create public static variable in app.xaml.cs . read command line parameter value in main method and assign it to public static variable. that can be accessed in viewmodel using App.variablename.
2) create environment variable like System.Environment.SetEnvironmentVariable("CmdLineParam", "u") and later use it in viewmodel with Environment.GetEnvironmentVariable("CmdLineParam").
I want to ask which approach is good considering MVVM pattern and if there is better method to achieve this.
Passing a parameter to the CanExecute and Execute methods A parameter can be passed through the "CommandParameter" property. Once the button is clicked the selected address value is passed to the ICommand. Execute method. The CommandParameter is sent to both CanExecute and Execute events.
In MVC, controller is the entry point to the Application, while in MVVM, the view is the entry point to the Application.
I do not think that this issue is related to MVVM at all. A good way to make the command line arguments available to a view model might be to (constructor) inject a service. Let's call it IEnvironmentService
:
public interface IEnvironmentService
{
IEnumerable<string> GetCommandLineArguments();
}
The implementation would then use Environment.GetCommandLineArgs
(which returns a string array containing the command-line arguments for the current process):
public class MyProductionEnvironmentService : IEnvironmentService
{
public IEnumerable<string> GetCommandLineArguments()
{
return Environment.GetCommandLineArgs();
}
}
Your view model would then look like this:
public class MyViewModel
{
public MyViewModel(IEnvironmentService service)
{
// do something useful here
}
}
All you have to do now is create and insert the production environment service at run-time (passing it yourself, having it created by IoC container etc.). And use a fake/mock one for unit testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With