在命令中初始化全局变量,并在另一个命令中使用它

本文关键字:命令 另一个 初始化 全局变量 | 更新日期: 2023-09-27 18:14:09

我的ViewModel包含一个变量,该变量在命令中初始化,我想在另一个命令中使用它。有两个窗口:第一个窗口包含一个按钮,该按钮启动第一个命令并打开第二个窗口。第二个窗口包含启动第二个命令的按钮。第二个命令需要第一个命令初始化的变量。这两个命令都是在ViewModel中实现的。

问题:当第二个窗口打开时,由第一个命令初始化的变量已经失去了它的值(空字符串),我不明白为什么。

我怎样才能实现呢?

在命令中初始化全局变量,并在另一个命令中使用它

这是我的代码(从我的ViewModel类):

// TextForThisWindow is a global variable declared in this class.
...
void firstCommandExecute()
    {
        TextForThisWindow = "Text";
        System.Windows.Application.Current.MainWindow.Hide();
        secondWindow sw = new secondWindow(Text);
        sw .WindowStartupLocation = WindowStartupLocation.CenterScreen;
        sw .Show();
    }
    bool CanfirstCommandExecute()
    {
        return true;
    }

    public ICommand firstCommand{ get { return new RelayCommand(firstCommandExecute, CanfirstCommandExecute); } }

    void secondCommandExecute()
    {
        Info = "info";
        if (TextForThisWindow.Contains("X"))
        {
            Selected = "X";
        }
        PathOfSelectedInfo = img.getPathOfSelectedInfo(ImagePathM1, Info);
        path = PathOfSelectedInfo;
        thirdWindow tw= new thirdWindow("Text" + Selected);
       tw.WindowStartupLocation = WindowStartupLocation.CenterScreen;
       tw.Show();
    }
    CanthirdWindowExecute()
    {
        return true;
    }

    public ICommand secondCommand{ get { return new RelayCommand(secondCommandExecute, CansecondCommandbExecute); } }