C# Can';t从另一个类WPF更新MainWindow文本框
当我尝试从另一个类更新文本框时,为什么文本框无法更新 我已经在Email类中实例化了MainWindow类,但是当我尝试C# Can';t从另一个类WPF更新MainWindow文本框,c#,wpf,textbox,C#,Wpf,Textbox,当我尝试从另一个类更新文本框时,为什么文本框无法更新 我已经在Email类中实例化了MainWindow类,但是当我尝试 main.trending.Text += emailText; 我做错什么了吗?您应该绑定数据 型号 public class YourData : INotifyPropertyChanged { private string _textBoxData; public YourData() { } public string TextBoxDat
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绑定
<TextBox Text="{Binding Path=Name2}"/>
见@sa_ddam213评论。不要执行类似于
mainwindowmain=newmainwindow()的操作代码>内部电子邮件类。相反,传递已有的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;
}
}
但我不认为这是最佳实践。我想我只是尽量让它接近您现有的代码。如果您在电子邮件类中实例化了一个主窗口,那么您已经更新了该窗口中的文本框,而不是整个应用程序的主窗口,您需要将对已实例化的主窗口的引用传递到电子邮件类中。我建议使用数据绑定。当数据更改时,将触发PropertyChange事件。绑定的问题会少一些。其他用户碰巧也有类似的问题。