简体   繁体   中英

Showing MessageBox in long running process

In an MVVM application I have a long running calculation that runs in legacy code.

That legacy code shows a MessageBox to ask the user if it shall continue.

Now I want this code to stick to MVVM as easy as possible and thought about handing in a callback to show the MessageBox and evaluating the result inside.

How can this be done the easiest?

Have often seen Action for callbacks, but I have no idea how to work with the bool inside the legacy code.

I want to pass the string to show in the MessageBox from the legacy code and return the decision (a bool) to the legacy code.

Please note: I do not have to do a bigger refactoring right now, but want to get rid of the MessageBox inside the legacy code right now.

Perhaps I can use a function like

    private bool ShowMessageBox(string text)
    {
        var result = MessageBox.Show(text, "", MessageBoxButton.YesNo);

        if (result.Equals(MessageBoxResult.Yes))
        {
            return true;
        }

        return false;
    }

-edit-

Should I use some

Action<string, Action<bool>> 

for the method signature? How can I access the bool in the legacy code?

Maybe you can use a delegate ?

For the method you showed, you can create a delegate like this:

public delegate bool ShowMessageBoxDelegate(string text);

Then let's say you have a property using the delegate as the type:

public ShowMessageBoxDelegate ShowMessageBoxDelegateProperty { get; set; }

Now if your ShowMessageBox method matches the signature of this delegate ...

public bool ShowMessageBox(string text)
{
    var result = MessageBox.Show(text, "", MessageBoxButton.YesNo);
    if (result.Equals(MessageBoxResult.Yes))
    {
        return true;
    }
    return false;
}

... then you could set it as the value of the ShowMessageBoxDelegateProperty property:

ShowMessageBoxDelegateProperty = ShowMessageBox;

Note the missing parenthesis. A delegate can also be multicast, which simply means that they can have more than one method attached to them:

ShowMessageBoxDelegateProperty += ShowMessageBox;

You can also use them as parameters in methods:

public void ProxyShowMessageBox(ShowMessageBoxDelegate showMessageBoxDelegate)
{
    if (showMessageBoxDelegate != null)
    {
        bool result = showMessageBoxDelegate("MessageBox message");
    }
}

You would then call it like this:

ProxyShowMessageBox(ShowMessageBox);

You can find out more from the Delegates Tutorial page at MSDN.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM