WPF get a command line argument into a viewmodel from mainwindow

Viewed 268

I'm trying to learn WPF and have a case where i have to pass a command line argument to a viewmodel. i was able to get the parameter from app.xaml and pass to MainWindow, but how do i get this parameter from mainwindow to the viewmodel. also if i add a constructor to the view model, then i cant declare it in in the datacontent in the xaml view - if i do it in the codebehind, i dont get the intellisense, which i another problem.

If you could point me to a simple example or even the pattern if need to do this type of thing that would be great.

View model

    public class RepoViewModel
    {
        private VcsRepo repo;
        public RepoViewModel()
        {
            // this is where i need that parameter from mainwindow
            this.repo = new VcsRepo(new Repository([my parameter]));
        }
        public VcsRepo Repo
        {
            get { return repo; }
            set { repo = value; }
        }
    }

The view

    <UserControl.DataContext>
        <local:RepoViewModel/>
    </UserControl.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding Repo.Files}"/>
    </Grid>
</UserControl>
2 Answers

This document provide command line argument.

https://docs.microsoft.com/en-us/dotnet/desktop/wpf/app-development/application-management-overview?view=netframeworkdesktop-4.8#processing-command-line-arguments

  1. Change StartUpUri to Startup in App.xaml.
<Application ..."
             Startup="App_OnStartup">
  1. Create MainWindow instance, include e.Args(in StartupEventArgs).
private void App_OnStartup(object sender, StartupEventArgs e)
{
   new MainWindow(e.Args).Show();
}
  1. Pass arguments from MainWindow to ViewModel.
public MainWindow(string[] eArgs)
{
   InitializeComponent();

   DataContext = new MainWindowViewModel(eArgs);
}

But i don't recommend this, how about dependency injection pattern? Like Prism etc..

Related