如何使用 WPF 和 MVVM 模式从 window 获取数据到另一个

How to get data from window to another with WPF and MVVM pattern

我构建了一个小型任务应用程序,在我的第一个 window 中,我有一个任务列表,当我单击“创建”按钮时,它会打开新的 windows 文本框,为它写一个标题和内容新任务。

我的需要是在我的第一个windows中获得第二个windows中写的标题和内容,以便将这个新任务添加到我的列表中。

我的代码如下所示:

主视图模型:

    public class MainViewModel : Notifyer
{

    ObservableCollection<Task> mTasks;
    public ObservableCollection<Task> Tasks { get { return this.mTasks; } set { this.mTasks = value; Notify("Tasks"); } }


    private ICommand m_ButtonAddCommand;
    public ICommand ButtonAddCommand { get { return m_ButtonAddCommand; } set { m_ButtonAddCommand = value; } }


    private ICommand m_ButtonDeleteCommand;
    public ICommand ButtonDeleteCommand { get { return m_ButtonDeleteCommand; } set { m_ButtonDeleteCommand = value; } }


    public MainViewModel()
    {
        ButtonAddCommand = new CommandHandler(() => add_task(), true);
        ButtonDeleteCommand = new CommandHandler(() => delete_task(), true);

        mTasks = new ObservableCollection<Task>();
        mTasks.Add(new Task("title1", "content1", true));
        mTasks.Add(new Task("title2", "content2", false));
    }

    private void add_task()
    {
        NewTaskWindow w = new NewTaskWindow();
        w.Show();
        //how to get my content ???
    }

    private void delete_task()
    {

    }
}

和新任务视图模型:

    public class NewTaskViewModel : Notifyer
{
    private ICommand m_ButtonAddCommand;
    public ICommand ButtonAddCommand { get { return m_ButtonAddCommand; } set { m_ButtonAddCommand = value; } }

    private String title;
    public String Title { get { return this.title; } set { this.title = value; Notify("Title"); } }

    private String content;
    public String Content { get { return this.content; } set { this.content = value; Notify("Content"); } }

    public NewTaskViewModel()
    {
        ButtonAddCommand = new CommandHandler(() => add_task(), true);
    }

    private void add_task()
    {
        Console.WriteLine(Title);
        Console.WriteLine(Content);
    }
}

您可以将模型传递到 window 而无需任何注入。没必要。

WindowModel windowModel = new WindowModel();
Window window = new Window(windowModel);

里面WindowClass

public Window(windowModel)
{
   DataContext = windowModel;
}

不要忘记为此 window 删除模型注入的引用。

您不应该在视图模型中创建 windows,而是使用依赖注入。要解决您的问题,请尝试以下操作:

private void add_task()
{
  NewTaskWindow w = new NewTaskWindow();
  var taskViewModel = ( NewTaskViewModel )w.DataContext;
  var title = taskViewModel.Title;
  var content = taskViewModel.Content;
  w.Show();
}