wpf 从另一个窗口中的一个窗口访问变量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26452792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access variable value from one window in another one
提问by James
I'm relatively new to C# and I have an question regarding how to access a variable from one window in another one. I want to do something like this:
我对 C# 比较陌生,我有一个关于如何从另一个窗口中的一个窗口访问变量的问题。我想做这样的事情:
public partial class MainWindow : Window
{
int foo=5;
....
}
and in window2:
并在窗口 2 中:
public partial class Window2: Window
{
int bar=foo;
}
How should I do that? Thanks in advance...
我该怎么做?提前致谢...
采纳答案by Vano Maisuradze
public class WindowBase : Window
{
protected static int foo = 5;
public int Foo
{
get
{
return foo;
}
set
{
foo = value;
}
}
}
public partial class Window1 : WindowBase
{
public Window1()
{
int bar = base.Foo;
}
}
public partial class Window2 : WindowBase
{
public Window2()
{
int bar = base.Foo;
}
}
回答by ProgramFOX
You could put these variables into a static class:
您可以将这些变量放入静态类中:
static class MyVariables
{
public static int foo;
}
In MainWindow, you can set the value of this variable:
在 MainWindow 中,您可以设置此变量的值:
MyVariables.foo = 5;
And in Window2, you can request the value:
在 Window2 中,您可以请求该值:
int bar = MyVariables.foo;
回答by Shaharyar
First of all you'll have to make your variable public:
首先,您必须创建变量public:
public int foo = 5;
For accessing, create instance of MainWindow:
要访问,请创建以下实例MainWindow:
MainWindow mw = new MainWindow();
bar = mw.foo;
回答by Anuj Yadav
You can do it in multipleways. It depends upon your usage though.
您可以通过多种方式做到这一点。不过,这取决于您的使用情况。
You can expose properties from your Window2 (assuming this form is invoked by MainWindow).
您可以从 Window2 公开属性(假设此表单由 MainWindow 调用)。
public partial class Window2: Window
{
public string Name {get; set;}
}
Then in MainWindow you can set this property.
然后在 MainWindow 中您可以设置此属性。
OrYou can create a singeltonas data share. Though, I will not recommend that.
或者您可以创建一个单例作为数据共享。虽然,我不会推荐那个。
orYou can also refer to this linkbut assuming you are just starting C# I think it might be slightly complicated.
或者您也可以参考此链接,但假设您刚开始使用 C#,我认为它可能有点复杂。

