App.xaml.cs中的参考对象在新窗口中

时间:2015-10-15 14:21:47

标签: c# wpf xaml

我尝试创建一个对象,该对象将保存应用程序在运行时期间全局需要的任何值。我以为我使用App.xaml.cs,因为这是应用程序的核心,如果我理解正确,因为该代码首先运行并保存在内存中。

在此帖子底部的代码.inProgress部分出现此错误:

  

'应用'不包含' inProgress'的定义没有延伸   方法' inProgress'接受类型' App'的第一个参数。可能   发现(您是否缺少using指令或程序集引用?)

App.xaml.cs

public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            //Startup
            Window main = new MainWindow();
            main.Show();

            //Bind Commands
            Classes.MyCommands.BindCommandsToWindow(main);

            //Create runtime objects
            var runtime = new runtimeObject();
        }

        public static explicit operator App(Application v)
        {
            throw new NotImplementedException();
        }
    }
    /// <summary>
    /// Global values for use during application runtime
    /// </summary>
    public class runtimeObject
    {
        private bool _inProgress = false;

        public bool inProgress
        {
            get { return _inProgress; }
            set { _inProgress = value; }
        }
    }

这里我试图访问runtime对象,以便我可以看到应用程序是否可以关闭,请记住这可能不需要,但我需要做类似这样的任务关闭窗户。

课程&gt; Commands.cs

bool inProgress = (System.Windows.Application.Current as App).inProgress;

1 个答案:

答案 0 :(得分:1)

看起来您需要添加一个属性来访问运行时对象。目前,您只是在OnStartup方法中创建实例。将该实例分配给属性:

public partial class App : Application
{
    public static runtimeObject runtime { get; set; };

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        //Startup
        Window main = new MainWindow();
        main.Show();

        //Bind Commands
        Classes.MyCommands.BindCommandsToWindow(main);

        // Create runtime objects
        // Assign to accessible property.
        runtime = new runtimeObject();            
    }

    public static explicit operator App(Application v)
    {
        throw new NotImplementedException();
    }
}

然后从命令逻辑中访问该属性:

public static void CloseWindow_CanExecute(object sender,
                       CanExecuteRoutedEventArgs e)
    {
        if (App.runtime.inProgress == true)
        {
            e.CanExecute = false;
        }
        else
        {
            e.CanExecute = true;
        }
    }