C#:从其他类更改主窗口的WindowState

时间:2019-01-02 14:51:59

标签: c# wpf

我有一个窗口中最默认的类,而我从窗口中调用了第二个类。我需要从第二个类中更改WindowState窗口的MainWindow,但是当我尝试通过以下方式进行操作时:MainWindow.WindowState = WindowState.Normal;会给我这个错误:An object reference is required for the non-static field, method, of property 'Window.WindowState'

MainWindow.xaml.cs

namespace Client_Patcher
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

UnminimizeApplicationCommand.cs

namespace Client_Patcher
{
    public class UnminimizeApplicationCommand : ICommand
    {
        public UnminimizeApplicationCommand(WindowState d)
        {
        }

        public bool CanExecute(object parameter)
        {
            throw new NotImplementedException();
        }

        public void Execute(object parameter)
        {
            //Need to change WindowState property of a MainWindow here.
        }

        public event EventHandler CanExecuteChanged;

        event EventHandler ICommand.CanExecuteChanged
        {
            add
            {
                throw new NotImplementedException();
            }

            remove
            {
                throw new NotImplementedException();
            }
        }
    }
}

我也尝试这样做:

namespace Client_Patcher
{
    public partial class MainWindow : Window
    {
        public MainWindow AppWindow { get; }

        public MainWindow()
        {
            InitializeComponent();
            AppWindow = this;
        }
    }
}

MainWindow.AppWindow.WindowState = WindowState.Normal;方式调用,但给出相同的错误。怎么办?

2 个答案:

答案 0 :(得分:2)

发生此错误是因为您将MainWindow当作静态对象对待。但实际上并非如此。考虑到这一点,现在再次阅读错误消息时,您将意识到它可以准确地告知您有关此问题的信息。为了解决这个问题

Application.Current.MainWindow.WindowState = WindowState.Normal;

在您的 Execute 回调中

答案 1 :(得分:-2)

我建议使用一种称为“ IoC容器”的东西

创建一个静态类。

 public static IoC
 {
     private static Window _window;
     // The main window instance for your app
     public static Window Window => _window;

     // Here you pass your application's "main" window instance.
     // So all window related intractability happens only from this clas
     public static InitializeDI(Window window)
     {

         _window = window;


}

}

注意: 您应该真正在应用程序启动的Main()方法中调用此方法