可闭tabitem.如何添加文本框



我正在开发一个多线程应用程序,它是一个新的"可关闭的";TAB为每个新线程打开。我从这个网站得到了可关闭表项的代码,但我也想在表项中有一个文本框。我累了在运行期间从主方法添加文本框,但它不能从创建后的线程访问。实现这一目标的最佳方式是什么?我正在寻找最好的方法来添加一个文本框到可关闭的选项卡,我可以从其他工作线程编辑。

编辑:

我添加了一些示例代码来展示我想要实现的目标。

namespace SampleTabControl
{
  public partial class Window1 : Window
  {
    public static Window1 myWindow1;
    public Window1()
    {
      myWindow1 = this;
      InitializeComponent();
      this.AddHandler(CloseableTabItem.CloseTabEvent, new RoutedEventHandler(this.CloseTab));      
    }
    private void CloseTab(object source, RoutedEventArgs args)
    {
      TabItem tabItem = args.Source as TabItem;
      if (tabItem != null)
      {
        TabControl tabControl = tabItem.Parent as TabControl;
        if (tabControl != null)
          tabControl.Items.Remove(tabItem);
      }
    }
    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
      Worker worker = new Worker();
      Thread[] threads = new Thread[1];
      for (int i = 0; i < 1; i++)
      {
        TextBox statusBox = new TextBox();
        CloseableTabItem tabItem = new CloseableTabItem();
        tabItem.Content = statusBox;
        MainTab.Items.Add(tabItem);
        int index = i;
        threads[i] = new Thread(new ParameterizedThreadStart(worker.start));
        threads[i].IsBackground = true;
        threads[i].Start(tabItem);
      }     
    }
  }
}

这是Worker类

namespace SampleTabControl
{
  class Worker
  {
    public CloseableTabItem tabItem;
    public void start(object threadParam)
    {
      tabItem = (CloseableTabItem)threadParam;
      Window1.myWindow1.Dispatcher.BeginInvoke((Action)(() => { tabItem.Header = "TEST"; }), System.Windows.Threading.DispatcherPriority.Normal);
      //Window1.myWindow1.Dispatcher.BeginInvoke((Action)(() => { tabItem.statusBox.Text //statusbox is not accesible here= "THIS IS THE TEXT"; }), System.Windows.Threading.DispatcherPriority.Normal);
      while (true)
      {
        Console.Beep();
        Thread.Sleep(1000);
      }
    }
  }
}

在我注释掉的那一行,statusBox是不可访问的

看了你的编辑后,很明显我原来的帖子没有回答原来的问题。

我认为以你想要的方式访问文本框,你需要强制转换tabItem。内容到文本框。

像下面这样可以

TextBox t = tabItem.Content as TextBox;
if (t != null)
    Window1.myWindow1.Dispatcher.BeginInvoke((Action)(() => { t.Text = "THIS IS THE TEXT";}), System.Windows.Threading.DispatcherPriority.Normal);

WPF不能修改在不同线程上创建的项

如果你还没有,我强烈建议你看看MVVM设计模式。这将UI层从业务逻辑层中分离出来。您的应用程序成为您的ViewModel类,UI层(视图)只是一个漂亮的界面,允许用户轻松地与ViewModels交互。

这意味着你所有的UI组件将共享一个线程,而你长时间运行的进程,如检索数据或处理数字,都可以安全地在后台线程上完成。

例如,您可以将TabControl.ItemsSource绑定到ObservableCollection<TabViewModels>,当您执行AddTabCommand时,您将启动一个新的后台工作程序,将新的TabViewModel添加到MainViewModel.TabViewModels集合中。

一旦后台worker完成它的工作。UI将自动得到通知,集合中有一个新项目,并将使用您指定的任何DataTemplate在TabControl中为您绘制新的TabItem

最新更新