[英]How to run a thread from a page in mainwindow ? (WPF)
I created a page and added a button to this page. 我创建了一个页面并在此页面中添加了一个按钮。
And I put this page in a frame in the main window. 我把这个页面放在主窗口的框架中。
MainUi.Content = new Page1();
I want to start a thread in mainwindow when I click the button. 我想在单击按钮时在主窗口中启动一个线程。
In MainWindow 在MainWindow
namespace WpfApp3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void SendMessage()
{
MessageBox.Show("This is a test massage.");
//And more
}
}
In Page 在页面
namespace WpfApp3.Pages
{
public partial class Page1: Page
{
public Page1()
{
InitializeComponent();
}
private void SendMessage_Click(object sender, RoutedEventArgs e)
{
SendMessage();
//I want run this thread from here
}
}
}
Thanks. 谢谢。
You could inject the Page
with a reference to the window as suggested by @Nawed Nabi Zada, or you could get a reference to the parent window of the page using the static Window.GetWindow
method: 您可以按照@Nawed Nabi Zada的建议为
Page
注入窗口引用,或者您可以使用静态Window.GetWindow
方法获取对页面父窗口的引用:
private void SendMessage_Click(object sender, RoutedEventArgs e)
{
MainWindow win = Window.GetWindow(this) as MainWindow;
win.SendMessage();
}
In your Page constructor add a parameter for MainWindow 在Page构造函数中,为MainWindow添加一个参数
private MainWindow _mainWindow;
public Page1(MainWindow mainWindow)
{
InitializeComponent();
_mainWindow = mainWindow;
}
Then you can call the message from there: 然后你可以从那里调用消息:
private void SendMessage_Click(object sender, RoutedEventArgs e)
{
SendMessage();
//I want run this thread from here
_mainWindow.SendMessage();
}
Alternative: 替代方案:
Make your method static: 使您的方法静态:
public static void SendMessage()
{
MessageBox.Show("This is a test massage.");
//And more
}
private void SendMessage_Click(object sender, RoutedEventArgs e)
{
MainWindow.SendMessage();
//I want run this thread from here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.