【问题标题】:Initialize a global variable in a Command and use it in another Command在一个命令中初始化一个全局变量并在另一个命令中使用它
【发布时间】:2017-03-04 04:19:15
【问题描述】:

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

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

我该如何实现?

【问题讨论】:

  • “命令”是什么意思?
  • C# 没有全局变量。不过,您可以使用类成员属性或static 属性。如果不了解有关您的代码的一些基本信息,则无法告诉您哪个更好。命令是否属于不同的类?
  • "第一个Command初始化的变量丢失了它的值(空字符串),我不明白为什么。" - 啊,所以你要求我们告诉你你的代码在那里做什么。在没有看到的情况下。让我看看nuget是否还有塔罗牌和读心包……
  • 好的,所以我不确定如何解决您的代码问题,但不要在满月下进行任何长途旅行。干杯!
  • 什么是静态的?

标签: c# wpf mvvm command viewmodel


【解决方案1】:

这是我的代码(来自我的 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); } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    相关资源
    最近更新 更多