[英]WPF Access window created on different UI thread
I created new Window on a different thread because it has heavy UI operations, that was done to keep my main window run smoothly. 我在不同的线程上创建了新的Window,因为它具有大量的UI操作,这样做是为了使主窗口保持平稳运行。 Everything works perfectly.
一切正常。
But here is the question: 但这是一个问题:
How I can access newly created window? 如何访问新创建的窗口?
After calling Dispatcher.Run()
I can not manipulate visualisationWindow
anymore. 调用
Dispatcher.Run()
我无法再操纵visualisationWindow
。 I want to keep access to that newly created window object. 我想继续访问该新创建的窗口对象。
Here is how my window created: 这是我的窗口的创建方式:
private void CreateVisualisationWindow()
{
Thread VisualisationWIndowThread = new Thread(new ThreadStart(ThreadStartingPoint));
VisualisationWIndowThread.SetApartmentState(ApartmentState.STA);
VisualisationWIndowThread.IsBackground = true;
VisualisationWIndowThread.Start();
}
private void ThreadStartingPoint()
{
Visualisation visualisationWindow = new Visualisation();
visualisationWindow.Show();
System.Windows.Threading.Dispatcher.Run();
}
Also I tried accessing it through System.Windows.Threading.Dispatcher.FromThread(VisualisationWIndowThread)
but seems I misunderstand some core things. 我也尝试通过
System.Windows.Threading.Dispatcher.FromThread(VisualisationWIndowThread)
访问它,但似乎我误解了一些核心内容。
I simulated your issue using two WPF Window objects and a timer to ensure that the Second Window was created before calling operations on it. 我使用两个WPF Window对象和一个计时器模拟了您的问题,以确保在调用第二个Window之前创建了第二个Window。 Below is my code sample and it updates the second Windows TextBox every five seconds:
下面是我的代码示例,它每五秒钟更新一次第二个Windows TextBox:
private Timer _timer;
private SecondWindow _secondWindow;
public MainWindow()
{
InitializeComponent();
CreateVisualisationWindow();
_timer = new Timer(Callback);
_timer.Change(5000, 5000);
}
private void Callback(object state)
{
UpdateSecondWindowText();
}
private void CreateVisualisationWindow()
{
Thread VisualisationWIndowThread = new Thread(ThreadStartingPoint);
VisualisationWIndowThread.SetApartmentState(ApartmentState.STA);
VisualisationWIndowThread.IsBackground = true;
VisualisationWIndowThread.Start();
}
private void ThreadStartingPoint()
{
_secondWindow = new SecondWindow();
_secondWindow.SecondWindowTextBlock.Text = "Hello";
_secondWindow.Show();
Dispatcher.Run();
}
private void UpdateSecondWindowText()
{
_secondWindow.Dispatcher.BeginInvoke(new Action(() =>
{
_secondWindow.SecondWindowTextBlock.Text = _secondWindow.SecondWindowTextBlock.Text + " World";
}));
}
So the trick is, you need to call the Dispatcher on the second Window in order to gain access to it. 因此,诀窍是,您需要在第二个Window上调用Dispatcher才能访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.