【问题标题】:WPF get a command line argument into a viewmodel from mainwindowWPF 从主窗口获取命令行参数到视图模型中
【发布时间】:2021-06-20 18:30:02
【问题描述】:

我正在尝试学习 WPF,并且有一个案例我必须将命令行参数传递给视图模型。我能够从 app.xaml 获取参数并传递给 MainWindow,但是我如何从 mainwindow 获取这个参数到 viewmodel。此外,如果我向视图模型添加构造函数,则无法在 xaml 视图的数据内容中声明它 - 如果我在代码隐藏中执行此操作,我将无法获得智能感知,这是另一个问题。

如果你能指出一个简单的例子,或者如果需要做这种事情的模式,那就太好了。

查看模型

    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; }
        }
    }

景色

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

【问题讨论】:

    标签: wpf mvvm viewmodel


    【解决方案1】:

    最简单的方法是使用Environment.GetCommandLineArgs()

    https://docs.microsoft.com/en-us/dotnet/api/system.environment.getcommandlineargs

    【讨论】:

      【解决方案2】:

      本文档提供命令行参数。

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

      1. App.xaml 中将StartUpUri 更改为Startup
      <Application ..."
                   Startup="App_OnStartup">
      
      1. 创建MainWindow 实例,包含e.Args(在StartupEventArgs 中)。
      private void App_OnStartup(object sender, StartupEventArgs e)
      {
         new MainWindow(e.Args).Show();
      }
      
      1. 将参数从 MainWindow 传递给 ViewModel。
      public MainWindow(string[] eArgs)
      {
         InitializeComponent();
      
         DataContext = new MainWindowViewModel(eArgs);
      }
      

      但我不推荐这个,依赖注入模式怎么样?比如Prism等等。

      【讨论】:

      • 我实际上完全按照你说的做了,但我仍然卡住的地方是将该参数从主窗口获取到另一个视图模型中,该视图模型需要它作为构造视图模型类的参数。我猜那是依赖注入进来的。
      猜你喜欢
      • 2018-04-26
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      相关资源
      最近更新 更多