【问题标题】:Change value of var from outside the windows从窗外更改 var 的值
【发布时间】:2016-04-12 06:56:28
【问题描述】:

在 WPF 上,我有打开 form2 的窗口 form 1

form2我有

 public partial class form2 : Window
    {

        public int temp1;

        public form2()
        {
            InitializeComponent();

            temp1 =123 ;
            this.tempTextBox.Text = temp1.ToString();

        }

    }

form1 我想打开form2 但编辑temp1 的值 我想做的是:

    Window newWind = new form2();
    (newWind as form2).temp1=555;
    newWind.Show();

但是当form 2 打开时,我看到tempTextBox = 123

我想去那里看看555

请问我该怎么做?

谢谢!

【问题讨论】:

  • temp1 的值是多少...您必须将 tempTextBox 的值重置为 temp1 才能看到更改
  • 您正在设置 temp1 值,但我认为您从未设置过文本框文本。您在“this.tempTextBox.Text = temp1.ToString()”形式的初始化中将其设置为 123,但随后设置了变量,这对更改文本框没有任何作用。我想如果你放一个断点并检查 temp1,它会保存 555。你只需要更新文本框。
  • 您将tempTextBox.Text 设置为该值,而不是绑定它。要正确设置绑定,您需要 a) 实现 INotifyPropertyChanged 以便属性更改通知起作用,b) 使 temp1 成为具有 get/set 访问器的属性,以及 c) 将 tempTextBox.Text 绑定到 temp1 属性。网上有很多例子。或者,只需像 Aaron 所说的那样,让属性的 set 访问器更新文本框的值。

标签: c# wpf


【解决方案1】:

将其更改为属性,修改setter中的文本框文本。

private int _temp1;
public int temp1{
get { return _temp1; }
set { 
    _temp1= value; 
    this.tempTextBox.Text = value;
    }
}

【讨论】:

  • 这是正确答案。解释原因:您在构造函数期间从 temp1 字段设置 Text,然后在稍后更改 temp1 字段时无法重新设置 Text。
猜你喜欢
  • 2021-07-08
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2022-11-15
  • 1970-01-01
  • 2019-11-23
  • 2010-11-20
  • 1970-01-01
相关资源
最近更新 更多