[英]Can't update MainWindow textbox from another class WPF
当我尝试从另一个班级更新文本框时,为什么我的文本框无法更新?
我已经在我的Email类中实例化了MainWindow类,但是当我尝试这样做时
main.trending.Text += emailText;
难道我做错了什么?
您应该绑定数据。
模型
public class YourData : INotifyPropertyChanged
{
private string _textBoxData;
public YourData()
{
}
public string TextBoxData
{
get { return _textBoxData; }
set
{
_textBoxData = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("TextBoxData");
}
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
XAML绑定
在Codebehind中设置数据上下文
this.DataContext = YourData;
绑定属性
<TextBox Text="{Binding Path=Name2}"/>
参见@ sa_ddam213注释。 不要做类似MainWindow main = new MainWindow();
在Email类中。 而是传递您已经拥有的MainWindow对象。 以下代码将起作用:
public class MainWindow
{
public void MethodWhereYouCreateEmailClass()
{
Email email = new Email;
email.Main = this;
}
}
public class Email
{
public MainWindow main;
public void MethodWhereYouSetTrendingText()
{
main.trending.Text += emailText;
}
}
但是我没有说这是最佳实践。 我只是想让它接近您现有的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.