问题
I have a window and a Frame within it. in that Frame, i open many pages which i would like to close by clicking on "Close" button , the problem is the page can't see my frame i tried to write in an event a close button in a page method to execute another event in a main window because it's easy on a main window to see a frame , but it's not working. here is my code in a page
private void closebt_MouseDown(object sender, MouseButtonEventArgs e)
{
var main = new MainWindow();
main.Exitbt_PreviewKeyDown(main.Exitbt, e);
}
and here is a code in a main window
internal void Exitbt_PreviewKeyDown(object sender, MouseButtonEventArgs e)
{
ProjectorFrame.Content = "";
MessageBox.Show("done");
}
Although the message show but it's not close page please help me.
回答1:
I don't know why you create another MainWindow instance inside the closebt_MouseDown hander, but I hope the following code would helpful for you:
private void closebt_MouseDown(object sender, MouseButtonEventArgs e)
{
MainWindow main = Application.Current.MainWindow as MainWindow;
if (main != null)
{
main.Exitbt_PreviewKeyDown(main.Exitbt, e);
main.Close();
}
}
Edited:
I supposed that the main Window object of your application is MainWindow
, so I thought that the previous code could get your application window close.
But as you commented, Application.Current.MainWindow
is different from MainWindow
, and the main
became null
.
Therefore, I think the simple way to get the main Window object is to create the following constructor in your page class to keep the reference:
class YourPageClass
{
public YourPageClass(MainWindow mainWindow)
{
main = mainWindow;
}
private MainWindow main;
(snip)
}
Then, create this instance with passing main Window object:
// somewhere in MainWindow code where instantiate your page object
var page = new YourPageClass(this);
By doing that, you can get the main Window object. So now, you can close your Window object as follows:
// in YourPageClass code
private void closebt_MouseDown(object sender, MouseButtonEventArgs e)
{
if (main != null)
{
main.Exitbt_PreviewKeyDown(main.Exitbt, e);
main.Close();
}
}
来源:https://stackoverflow.com/questions/25708309/close-page-within-frame-in-a-wpf