【问题标题】:How to pass the model information to a user control view model that is in a main window?如何将模型信息传递给主窗口中的用户控件视图模型?
【发布时间】:2022-01-19 03:31:42
【问题描述】:

我正在尝试学习 MVVM 模式,使用 WPF 做一个简单的 GUI。它只是Autocad 的一个简单插件,带有一个显示模型的一些信息的模式窗口。

我有两个带有各自视图和视图模型的用户控件。我在单个窗口/对话框中显示这些用户控件。其中一个用户控件需要显示一些信息,在 DataGrid 中表示一个简单的列表(模型)。

正如我之前所说,该用户控件的模型是现有列表。我需要将列表信息传递给视图模型,但我正在努力解决这个问题。我正在考虑将它作为参数传递给 MainWindow 构造函数,然后传递给相应的视图模型,但听起来不是一个好主意。

在这种情况下我有什么选择?

我正在使用 MVVM 工具包。

谢谢!

【问题讨论】:

    标签: wpf mvvm mvvm-toolkit


    【解决方案1】:

    您可以使用WeakReferenceMessenger/StrongReferenceMessenger 将消息从一个视图模型发送到另一个视图模型:

    // Create a message
    public class LoggedInUserChangedMessage : ValueChangedMessage<User>
    {
        public LoggedInUserChangedMessage(User user) : base(user)
        {
        }
    }
    
    // Register a message in some module
    WeakReferenceMessenger.Default.Register<LoggedInUserChangedMessage>(this, (r, m) =>
    {
        // Handle the message here, with r being the recipient and m being the
        // input message. Using the recipient passed as input makes it so that
        // the lambda expression doesn't capture "this", improving performance.
    });
    
    // Send a message from some other module
    WeakReferenceMessenger.Default.Send(new LoggedInUserChangedMessage(user));
    

    更多信息请参考docs

    【讨论】:

      猜你喜欢
      • 2013-06-04
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      相关资源
      最近更新 更多