我在c#中使用3个不同的窗口创建了一个WPF应用程序,Home.xaml, Name.xaml, Config.xam
l。我想在Home.xaml.cs
中声明一个我可以在其他两种形式中使用的变量。我尝试了public string wt = "";
但是没有用。
如何通过所有三种形式使其可用?
答案 0 :(得分:22)
正确的方法,特别是如果您想转移到XBAPP,是将其存储在
中Application.Current.Properties
这是一个Dictionary对象。
答案 1 :(得分:14)
为避免在Windows和用户控件之间传递值,或创建静态类以复制WPF中的现有功能,您可以使用:
App.Current.Properties["NameOfProperty"] = 5;
string myProperty = App.Current.Properties["NameOfProperty"];
这是上面提到的,但语法有点偏。
这提供了应用程序中的全局变量,可以从其中运行的任何代码访问。
答案 2 :(得分:11)
您可以使用静态属性:
public static class ConfigClass()
{
public static int MyProperty { get; set; }
}
修改强>
这里的想法是创建一个包含所有“常用数据”的类,通常是配置。当然,您可以使用任何类,但建议您使用静态类。 您可以像这样访问此属性:
Console.Write(ConfigClass.MyProperty)
答案 3 :(得分:1)
你可以在这里做两件不同的事情(其中包括最初想到的两件事)。
您可以在Home.xaml.cs上将变量设为静态
public static string Foo =“”;
您可以将变量传递给所有三种形式。
我会自己选择#2,如果有必要,创建一个包含我需要的数据的单独类。然后每个类都可以访问数据。
答案 4 :(得分:0)
<强> 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()
答案 5 :(得分:0)
就像前面提到的其他人一样,可以使用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();
另一方面,请注意,将静态类用作c#中的全局变量被认为是一种不好的做法(这就是为什么没有正式的全局实现的原因),但是我认为这是我懒惰时的捷径哈哈。不应在专业环境中使用。