I have a problem here. In project A I have a wpf, I referred the project B, and in this wpf , I create a winform b which defined in Project B.

When I closing the form b, I want to also close the wpf.

Since I already referred project B in project A. How can I close the wpf?

The code is like this:

using projectB;
namespace projectA    
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            function();
        }

        public void function()
        {
            form = new formb();
            form.Show();
        }
    }
}

.

namespace projectB
{       
    public partial class formb : WinFormBase
    {
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Dispose();
            // how to also close the wpf(MainWindow) here?
        }
    }
}
有帮助吗?

解决方案

Make an object responsible for keeping track of all the windows. Make sure this object opens all windows.

Put all these windows in a list and just walk the list to close all the windows.

Using Application.Current.Shutdown might cause windows getting closed without saving state.

Try to implement a graceful shutdown.

Alternative

Make a global event and have all the windows listen to it. When the event is raised, have each window close itself.

Example

public static class WindowManager
{
    public static event EventHandler<EventArgs> ClosingWindows;

    public static void CloseWindows()
    {
        var c = ClosingWindows;
        if (c != null)
        {
            c(null, EventArgs.Empty);
        }
    }
}

In each window register for this event and respond to it. Note that you will have to decide when you call the WindowManager.CloseWindows method. In this example it is put in a click handler of a button but you might want to add it to other event handlers as well (what happens when the user presses Alt-F4 or clicks the red close button on the top right)

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        // register for the other windows closing
        WindowManager.ClosingWindows += WindowManager_ClosingWindows;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        WindowManager.CloseWindows();
    }

    void WindowManager_ClosingWindows(object sender, EventArgs e)
    {
        // when other windows close, close this as well
        this.Close();
    }

    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);

        // when closed remove eventhandler
        WindowManager.ClosingWindows -= WindowManager_ClosingWindows;
    }
}

其他提示

Referring to the application as "the WPF" is a bit confusing.

To close the window, simply call Shutdown on the Application

Application.Current.Shutdown();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top