WPF Application using a global variable

自闭症网瘾萝莉.ら 提交于 2019-12-28 11:50:07

问题


I created a WPF application in c# with 3 different windows, Home.xaml, Name.xaml, Config.xaml. I want to declare a variable in Home.xaml.cs that I can use in both the other forms. I tried doing public string wt = ""; but that didn't work.

How can I make it usable by all three forms?


回答1:


The proper way, especially if you ever want to move to XBAPP, is to store it in

Application.Current.Properties

which is a Dictionary object.




回答2:


To avoid having to pass around values between windows and usercontrols, or creating a static class to duplicate existing functionality within WPF, you could use:

  • setting: App.Current.Properties["NameOfProperty"] = 5;
  • getting: string myProperty = App.Current.Properties["NameOfProperty"];

This was mentioned above, but the syntax was a little off.

This provides global variables within your application, accessible from any code running within it.




回答3:


You can use a static property:

public static class ConfigClass()
{
    public static int MyProperty { get; set; }
}

Edit:

The idea here is create a class that you holds all "common data", typically configurations. Of course, you can use any class but suggest you to use a static class. You can access this property like this:

Console.Write(ConfigClass.MyProperty)



回答4:


There are two different things you can do here (among others; these are just the two that come to mind first).

  1. You could make the variable static on Home.xaml.cs

    public static string Foo = "";

  2. You could just pass in the variable to all three forms.

I would go with #2, myself, and if necessary create a separate class that contains the data I need. Then each class would have access to the data.




回答5:


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>

code behind

Application.Current.FindResource("strApp").ToString()


来源:https://stackoverflow.com/questions/1161459/wpf-application-using-a-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!