我创建了一个页面,并在此页面上添加了一个按钮。
然后将此页面放在主窗口的框架中。
MainUi.Content = new Page1();
当我单击按钮时,我想在主窗口中启动一个线程。
在MainWindow中
namespace WpfApp3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void SendMessage()
{
MessageBox.Show("This is a test massage.");
//And more
}
}
页面内
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
}
}
}
谢谢。
答案 0 :(得分:2)
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:
private void SendMessage_Click(object sender, RoutedEventArgs e)
{
MainWindow win = Window.GetWindow(this) as MainWindow;
win.SendMessage();
}
答案 1 :(得分:0)
In your Page constructor add a parameter for 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
}