2013-11-22 41 views
0

为什么当我尝试从另一个类更新文本框时,文本框无法更新?无法从另一个类更新MainWindow文本框WPF

我实例化的主窗口类在我的电子邮件类,但是当我尝试做

main.trending.Text += emailText; 

难道我做错了什么?

+0

如果你实例化电子邮件类中的主窗口,那么你已经更新在该窗口中的整个应用程序的不是主窗口的文本框,您将需要向已经实例主窗口的引用传递到电子邮件类。 –

+0

我建议使用数据绑定。当数据更改时,PropertyChange事件将被触发。绑定可以减少麻烦。其他 – aDoubleSo

回答

0

你应该绑定你的数据。

模型

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绑定在代码隐藏

  1. 集数据上下文

    this.DataContext = YourData;

  2. 绑定属性

    <TextBox Text="{Binding Path=Name2}"/> 
    
0

见@ 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; 
    } 
} 

但是,我说这是最好的做法。我只是尽量保持它接近你我现有的代码。

+0

用户碰巧有类似的问题[这里](http://stackoverflow.com/questions/20085272/function-call-works-when-called-internally-from-in-its-control-but-not-externall/ )。 – har07

相关问题