wpf 从表单访问文本框值到另一个类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12157133/
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
Accessing Text Box Values from Form to another class
提问by Ibrahiem Rafiq
I have a WPF Application which contains a class called RateView.xaml.cs and MainWindow.xaml.cs
我有一个 WPF 应用程序,其中包含一个名为 RateView.xaml.cs 和 MainWindow.xaml.cs 的类
The MainWindow.xaml.cs contains three textboxes of which values I want to pass into the RateView.xaml.cs. The content of these textboxes can be changed by the end user but regardless of that I always want whatever the value is of the textbox to be going into rateview.xaml.cs.
MainWindow.xaml.cs 包含三个文本框,我想将其中的值传递给 RateView.xaml.cs。最终用户可以更改这些文本框的内容,但无论如何,我始终希望将文本框的任何值放入 rateview.xaml.cs。
How can this be done?
如何才能做到这一点?
I am a newbie to coding hence not sure, someone mentioned Get and Set statements, if so how can I do these?
我是编码的新手,因此不确定,有人提到了 Get 和 Set 语句,如果是这样,我该怎么做?
Currently I access my textboxes like this in the MainWindow:
目前,我在 MainWindow 中像这样访问我的文本框:
private float GetSomeNumber()
{
bool Number1 = false;
float parsedNumber1Value = 0.00F;
Number1 = float.TryParse(Number1_TextBox.Text, out parsedNumber1Value);
return parsedNumber1Value;
}
The GetSomeNumber() method is then passed to another seperate class to do some calculation with.
然后将 GetSomeNumber() 方法传递给另一个单独的类以进行一些计算。
On intital load it works of the value from my method, but once someone changes the value rateview.xaml.cs doesn't recognise this change and always uses the values that were first loaded.
在初始加载时,它使用我的方法中的值,但是一旦有人更改了值 rateview.xaml.cs 就无法识别此更改并始终使用首次加载的值。
Thanks
谢谢
回答by Tomtom
Just a small example (This is winforms)
只是一个小例子(这是winforms)
This is the mainwindow, where your textbox is:
这是主窗口,您的文本框位于:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
1
public string TextBox1Text
{
get { return textBox1.Text; }
set { textBox1.Text = value;
}
}
and this is a class where you want to interact with the textboxes:
这是一个您想要与文本框交互的类:
public class Test
{
public Test(Form1 form)
{
//Set the text of the textbox in the form1
form.TextBox1Text = "Hello World";
}
}
回答by Tomtom
To get and set the value of a textbox within another class/form you can do it with something like:
要在另一个类/表单中获取和设置文本框的值,您可以使用以下方法:
public string TextBox1Text
{ get { return textBox1.Text; }
set { textBox1.Text = value; } }

