2013-03-16 70 views
2

我在更新c#中的WPF表單中的TextBox文本時遇到問題。我編程式地創建了新的表單,並添加了一個Label和一個TextBox,並且我有一個變量temp,它表示來自我之前創建的某個緩衝區的一些字符串。但是,當我嘗試將文本設置爲標籤或文本框時,什麼也沒有發生。但是,我可以用新形式更改窗口標題。如何從另一個WPF表單設置WPF中的TextBox或Label文本

我的代碼是:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 

namespace BufferProba 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     BufferStream bfStream = new BufferStream(); 

     private static Action EmptyDelegate = delegate() { }; 

     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Window_Loaded(object sender, RoutedEventArgs e) 
     { 

      Thread t = new Thread(SetText); 
      t.SetApartmentState(ApartmentState.STA); 
      t.IsBackground = true; 
      t.Start(); 

     } 


     private void Button_Click_1(object sender, RoutedEventArgs e) 
     { 
      bfStream.put(tBox.Text.Trim()); 
      tBox.Text = ""; 
     } 


     public void SetText() 
     { 
      Thread.Sleep(5000); 

      Window myWindow = new Window(); 
      StackPanel stackPanel = new StackPanel { Orientation = Orientation.Vertical }; 
      TextBox tboxForm = new TextBox(); 
      Label szzr = new Label { Content = "" }; 
      stackPanel.Children.Add(szzr); 
      stackPanel.Children.Add(tboxForm); 
      myWindow.Content = stackPanel; 
      List<String> listaStringova = new List<String>(); 

      while (true) 
      { 
       Thread.Sleep(5000); 

       String temp = bfStream.get(); 
       listaStringova.Add(temp); 

       if (temp != "0") 
       { 
        //Console.WriteLine(temp); 
        myWindow.Title = temp; 
        szzr.Content = temp; 
        szzr.Background = new SolidColorBrush(Colors.Orange); 
        szzr.UpdateLayout(); 
        tboxForm.Text = temp; 
        myWindow.Show(); 

       } 
       else { 
        MessageBox.Show("Jebiga"); 
       } 

      } 
     } 


    } 
} 

回答

0

您需要確保它是一個的訪問文本框的UI線程。使用Dispatcher.CheckAccess方法,如果它返回false,則BeginInvoke一個UI線程。使用此信息,您應該可以在網上找到大量示例。

0

你應該在主線程上運行它。 你可以使用Dispatcher做同樣的事情 例如:

System.Windows.Application.Current.Dispatcher.Invoke(new Action(SetText()))