Muckers Mucker
Muckers Mucker

Reputation: 109

Controlling Window close from UserControl

I'm using the excellent MUI library https://mui.codeplex.com/ to create my WPF application.

Custom windows are implemented as User Control within a MUI Window. To open a window, create an instance of a Modern Window, passing a User Control as content. This, so far, works OK, but the problem I'm having is trying to control the parent window from the user control.

When I saying 'trying to control' I mean validating the window's close behaviour.

The user control is where I do all my editing of data etc and I want to prevent the parent window from closing if the user is editing data - ie. "Close Yes, no cancel" kind of thing.

I can successfully close the parent window from the user control but I cannot see how to do the reverse - i.e. stopping the window from closing.

Can someone please help?

Thanks

Upvotes: 4

Views: 1542

Answers (1)

Dtex
Dtex

Reputation: 2623

I don't know much about mui, but i think something like this should do the trick

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();

        Loaded += UserControl1_Loaded;
    }

    void UserControl1_Loaded(object sender, RoutedEventArgs e)
    {
        var window = Window.GetWindow(this);
        window.Closing += window_Closing;
    }

    void window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        if (!Valid()) // You can show a message box or whatever logic you want
            e.Cancel = true;
    }
}

Upvotes: 4

Related Questions