Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use Command line parameter in viewmodel (MVVM Model) wpf application

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.

like image 549
Kundan Bhati Avatar asked Oct 05 '13 11:10

Kundan Bhati


People also ask

How do you pass a command parameter in WPF MVVM?

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.

Is there controller in MVVM?

In MVC, controller is the entry point to the Application, while in MVVM, the view is the entry point to the Application.


1 Answers

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.

like image 145
meilke Avatar answered Nov 03 '22 14:11

meilke