简体   繁体   English

如何创建可以在应用程序中的任何位置设置/获取的Application-scope变量? (WPF / MVVM)

[英]How can I create Application-scope variable that can be set/get anywhere in the application? (WPF/MVVM)

I am writing a WPF application and trying to learn effective MVVM practices. 我正在编写WPF应用程序,并尝试学习有效的MVVM实践。 I have MenuItem buttons in my interface (inside MainWindow.xaml) and would like to bind their Command property to an ICommand I have created. 我的界面(位于MainWindow.xaml内部)中有MenuItem按钮,并希望将其Command属性绑定到我创建的ICommand。

When the application launches, I want a bool (that can be set/get from anywhere in the application) to be set to originally be set to false. 当应用程序启动时,我希望将bool(可以在应用程序中的任何位置进行设置/获取)设置为最初设置为false。 When the "File > New" MenuItem is activated, I want the command to fire off and check against the Application-scope variable in its "CanExecute" method, which is then supposed to enable or disable the MenuItem. 激活“文件>新建”菜单项后,我希望命令启动并检查其“ CanExecute”方法中的Application-scope变量,然后该方法应启用或禁用MenuItem。

My issue is that I cannot figure out where exactly is the best place to store/instantiate/etc this variable (or property?). 我的问题是我无法弄清楚存储/实例化/等该变量(或属性?)的最佳位置在哪里。

I have tried a multitude of different combinations, including implementing a singleton-pattern design with my "Workspace" class (which holds the boolean variable), and also I am now tinkering with static classes and variables. 我尝试了多种不同的组合,包括使用我的“ Workspace”类(包含布尔变量)实现单例模式设计,并且现在我还要修改静态类和变量。

My code is shown here: 我的代码如下所示:

XAML: XAML:

<MenuItem Header="_File">
            <MenuItem Header="_New Project" Command="{Binding NewProjectCommand, Source={StaticResource project}}"/>
            <MenuItem Header="_Open Project"/>
</MenuItem>

App.xaml.cs: App.xaml.cs:

public WorkspaceViewModel WorkspaceInfo { get; set; }

public partial class App : Application
{
    public App()
    {
        //Store variable here? How? And what is the best way to expose it to my Commands?
    }

}

WorkspaceViewModel.cs: WorkspaceViewModel.cs:

class WorkspaceViewModel : Workspace
{

}

NewProjectCommand.cs: NewProjectCommand.cs:

class NewProjectCommand : ICommand
{

    public NewProjectCommand(ProjectViewModel projectViewModel)
    {
    }

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        //Do an evaluation here using the new bool in App.xaml.cs
        //return true/false, based on the evaluation

    }

    public void Execute(object parameter)
    {
        //Perform steps here to switch the bool in App.xaml.cs, and perform other command functionality
    }
}

Workspace.cs: Workspace.cs:

class Workspace : INotifyPropertyChanged
{
    private bool _isProjectOpen;

    public bool IsProjectOpen
    {
        get { return _isProjectOpen; }
        set
        {
            _isProjectOpen = value;
            OnPropertyChanged();
        }
    }


    #region INotifyPropertyChanged members

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        var handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}

I am basically wanting to store a true/false value in the highest level of my application, that way I can get the variable in the "CanExecute" and set the variable in the "Execute" methods for all my ICommands, so all of my MenuItems will become enabled and disabled at the appropriate time. 我基本上是想在我的应用程序的最高级别中存储一个true / false值,这样我就可以在我的所有ICommands的“ CanExecute”中获取变量并在“ Execute”方法中设置该变量,因此MenuItems将在适当的时间启用和禁用。

I realize that this is a rather long-winded question, but any help is very much appreciated and if I need to post any additional information, I would be happy to do so! 我意识到这是一个相当棘手的问题,但是非常感谢您的帮助,如果我需要发布任何其他信息,我将很乐意这样做!

Thank you all in advance! 谢谢大家!

An "application-scope variable" can be declared as property in the App class: 可以在App类中将“应用程序范围变量”声明为属性:

public partial class App : Application
{
    public bool YourProperty { get; set; } // is false by default
}

Now the property "can be set/get from anywhere in the application" by 现在,属性“可以从应用程序中的任何位置设置/获取”

((App)Application.Current).YourProperty = true;

and

var propertyValue = ((App)Application.Current).YourProperty;

Store the value in the Properties dictionary of the static Application.Current instance: 将值存储在静态Application.Current实例的Properties字典中:

Application.Current.Properties["NameOfProperty"] = false;
var myProperty = (bool)Application.Current.Properties["NameOfProperty"];

Two Ways 两种方式
1.] Either save them as Project settings 1.]将它们另存为项目设置
Right click on project than click Properties and than go to settings 右键单击项目,然后单击属性,然后转到设置
Create your settings here . 在此处创建设置。
在此处输入图片说明 you can access or manipulate them programatically in your code 您可以在代码中以编程方式访问或操作它们

Properties.Settings.Default.SavedInputString

2.] Store them in custom xml file 2.]将它们存储在自定义xml文件中
Xml files are easy to create , read and update and its a fast way to load setting at run time Xml文件易于创建,读取和更新,并且是在运行时加载设置的快速方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在应用程序的框架中使用视图? (WPF MVVM) - How can I use a view from a framework in an application? (WPF MVVM) 如何在WPF应用程序中的任何地方获取调度程序 - How to get dispatcher anywhere in WPF application Keycloak in C# WPF Application: How can I access the roles of a given user/password in C# in a normal MVVM WPF application? - Keycloak in C# WPF Application: How can I access the roles of a given user/password in C# in a normal MVVM WPF application? 如何在WPF应用程序中全局设置文化? - How can i globally set the Culture in a WPF Application? 如何在 WPF 中创建在后台运行的应用程序 - How can I create an application in WPF that runs in background 如何获取 DataGrid 中选定行的集合? MVVM WPF - How can I get a collection of selected rows in the DataGrid? MVVM WPF 如何为WPF应用程序修复此代码? - How can I fix this code for WPF Application? 如何在应用程序中的任何地方丢失键盘范围? - How to lose keyboard scope anywhere in the application? 我如何使用wpf制作一个在运行时制作一个新应用程序的应用程序? - How can i make an application with wpf that makes an new application in runtime? 如何在不参考数据库的情况下在WPF MVVM应用程序中创建报表 - How do I create a report in a WPF MVVM application without refering to a database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM