【问题标题】:Passing Parm from App.xaml to ViewModel - Silverlight MVVM将 Parm 从 App.xaml 传递到 ViewModel - Silverlight MVVM
【发布时间】:2013-02-25 05:39:07
【问题描述】:

我有一个驻留在 App.xaml.cs 中的字符串 UserName,我需要将其带到 ViewModel 以填充控件。实现这一目标的最佳方法是什么?

【问题讨论】:

  • 它如何驻留在 App.xaml.cs 中?
  • 我将它作为 传递给 Application_Startup。它以 e.InitParams 的形式出现。我想将此用户持久保存到虚拟机

标签: silverlight mvvm


【解决方案1】:

您最常使用控制资源来访问 ViewModel 实例。 然后通过在 ViewModel 中定义的公共方法,您可以将参数传递给它。

((ViewModel1)this.Resources["ViewModel1"]).Test(p);

Test 是 ViewModel 中接收参数的公共方法。

【讨论】:

  • 谢谢。但是,当我的配对视图实例化 ViewModel 时,我失去了价值
【解决方案2】:

您可以发送包含该值的消息(例如 MvvmLight Messenger 类),ViewModel 将注册以接收它。

在 App.xaml.cs 中:

Messenger.Default.Send<string>(Username);

在 ViewModel 的构造函数中:

Messenger.Default.Register<string>(this, m => 
    {
        this.Username = m; // or whatever you need to do with the value
    });

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多