【发布时间】:2010-11-12 18:50:49
【问题描述】:
我用 c# 创建了一个 WPF 应用程序,有 3 个不同的窗口,Home.xaml, Name.xaml, Config.xaml。我想在Home.xaml.cs 中声明一个变量,我可以在其他两种形式中使用它。我尝试做public string wt = "";,但没有奏效。
我怎样才能使它适用于所有三种形式?
【问题讨论】:
标签: c# wpf global-variables
我用 c# 创建了一个 WPF 应用程序,有 3 个不同的窗口,Home.xaml, Name.xaml, Config.xaml。我想在Home.xaml.cs 中声明一个变量,我可以在其他两种形式中使用它。我尝试做public string wt = "";,但没有奏效。
我怎样才能使它适用于所有三种形式?
【问题讨论】:
标签: c# wpf global-variables
您可以使用静态属性:
public static class ConfigClass()
{
public static int MyProperty { get; set; }
}
编辑:
这里的想法是创建一个包含所有“公共数据”的类,通常是配置。当然,您可以使用任何类,但建议您使用静态类。 你可以像这样访问这个属性:
Console.Write(ConfigClass.MyProperty)
【讨论】:
您可以在这里做两件不同的事情(除其他外;这只是首先想到的两件)。
您可以在 Home.xaml.cs 上将变量设为静态
public static string Foo = "";
您可以将变量传递给所有三种形式。
我自己会选择#2,如有必要,我会创建一个包含我需要的数据的单独类。然后每个类都可以访问数据。
【讨论】:
正确的方法,尤其是如果您想迁移到 XBAPP,将其存储在
Application.Current.Properties
这是一个字典对象。
【讨论】:
为避免在窗口和用户控件之间传递值,或创建静态类来复制 WPF 中的现有功能,您可以使用:
App.Current.Properties["NameOfProperty"] = 5;
string myProperty = App.Current.Properties["NameOfProperty"];
上面提到过,但语法有点不对。
这在您的应用程序中提供了全局变量,可以从其中运行的任何代码访问。
【讨论】:
.ToString() 才能从属性中获取值,但除此之外,这对我来说很好,谢谢分享。 string myProperty = App.Current.Properties["NameOfProperty"].ToString();
App.xaml:
<Application x:Class="WpfTutorialSamples.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
StartupUri="WPF application/ResourcesFromCodeBehindSample.xaml">
<Application.Resources>
<sys:String x:Key="strApp">Hello, Application world!</sys:String>
</Application.Resources>
代码隐藏:
Application.Current.FindResource("strApp").ToString()
【讨论】:
正如其他人之前提到的那样,要么使用App.Current.Properties,要么创建一个静态类。
我在这里为那些需要更多静态类指导的人提供一个示例。
在解决方案资源管理器中右键单击您的项目名称
Add > New Item选择Class为其命名(我通常将其命名为 GLOBALS)
using System;
namespace ProjectName
{
public static class GLOBALS
{
public static string Variable1 { get; set; }
public static int Variable2 { get; set; }
public static MyObject Variable3 { get; set; }
}
}
using ProjectName
GLOBALS.Variable1 = "MyName"
Console.Write(GLOBALS.Variable1)
GLOBALS.Variable2 = 100;
GLOBALS.Variable2 += 20;
GLOBALS.Variable3 = new MyObject();
GLOBALS.Variable3.MyFunction();
关于单元测试和静态类/静态变量的说明
使用静态类来保存全局变量通常被认为是一种不好的做法,主要原因之一是它会严重阻碍正确对代码进行单元测试的能力。
但是,如果您需要可测试的代码并且您仍然想使用静态全局变量类,那么至少考虑使用单例模式来访问您的 GLOBALS。 [更多详情:https://jonskeet.uk/csharp/singleton.html]
下面是我的意思的一个有用的sn-p。将 GLOBALS 抽象化并移除静态,然后在 GLOBALS 类中添加以下内容:
private static GLOBALS instance = null;
/// <summary>
/// The configuration instance used by the application and unit tests
/// </summary>
public static GLOBALS Instance
{
get
{
if (instance == null)
{
//Create the default configuration provider
instance = new AppConfigConfiguration();
}
return instance;
}
set
{
instance = value;
}
}
AppConfigConfiguration(在上面的示例中)是派生自 GLOBALS 的特定于应用程序的设置类。单例模式还允许派生其他配置,并且可以选择在 Instance 属性上进行设置,这是在单元测试运行之前常见的情况,因此可以确保测试特定的设置。
【讨论】: