tags:

views:

26

answers:

1

So, I have a class, which goes as follows:

public class EditorUserControl : UserControl
{

    public EditorUserControl()
        : base()
    {
        this.IsVisibleChanged += new DependencyPropertyChangedEventHandler(
            EditorUserControl_IsVisibleChanged);
    }

    void EditorUserControl_IsVisibleChanged(
        object sender, 
        DependencyPropertyChangedEventArgs e)
    {
        if (IsEditing && !((bool)e.NewValue))
        {
            PressedButton pressedButton = PromptUser(new Buttons[] { 
                "Save changes to the object you just edited?",
                Buttons.Yes, 
                Buttons.No, 
                Buttons.Cancel });
            if(pressedButton == Buttons.Cancel)
            {
                CANCELTHETHING();
            }
        }
    }
}

In words - this class is a base for all entity editing controls and when it goes invisible (e.g. window is closed, tab changed etc.) I need to check if the user has made changes and prompt the user whether to save/discard/cancel. The save/discard are easy. The problem is with the third option (and it must be there) - I cannot figure out a way how could I cancel the source event that caused the visibility to change (as there is no way to get to that actual event). Is there a better way to do this functionality (that would not require signing up for all of the possible sources of events)?

A: 

I don't think it is possible to cancel the source (event) as you want to. Consider this line of code - EditorUserControl.Visibility = Visisibility.Hidden;

This will also cause the IsVisibleChanged event to fire, but there is no way to cancel a single line of code.

Your only option is to move the logic inside the IsVisibleChanged event handler to a method that will be called as appropriate by the application. For instance if you close the window then in the window_closing event handler you call the method and if the result is Button.Cancel then you cancel the closing event. If you change tabs then you handle a SelectionChanged event and again call the method and if you need to cancel then you set the selected tab index back to the previous value etc.

Marko
Well, I know that handling all of the events separately is one solution. But you never know until you ask - maybe there are some clever solutions to such a problem.
Jefim
Well as far as I know, it's not possible. And if you think about it logicaly, it's impossible to have a universal "cancel" method for a single line of code vs closing a window vs changing a tab...But as you said you never know, maybe there is a one size fits all solution to your problem that is a bit more elegant than handling all the events seperately.
Marko
After some investigations I came to a conclusion that this is indeed impossible as the initial event is inaccessible. Thanks for the answer, Marko. You were right.
Jefim