0
votes

I use MVVM light toolkit in WPF application and I get data from external source. My MainViewModel c'tor look like that:

    public MainViewModel()
    {
        try
        {
            GetData();
        }
        catch (Exception e)
        {
            //here i want to show error dialog
        }
    }

I cannot send message (like it done here) to view because ModelView is created before View so there is nobody that can receive message and show dialog. What is the right way to solve this problem?

2
are you using Dependency Injection?vidalsasoon

2 Answers

1
votes

You should only throw exceptions from the constructor if initialization fails. In this case you can start the retrieval of the data when the view is loaded. You can invoke a commmand of the VM from the loaded event with the use of Attached Command Behavior.

0
votes

Using the technique in the post you linked, I'd do something like this:

public MainViewModel()
{
    try
    {
        GetData();
    }
    catch (Exception e)
    {
        Messenger.Default.Send(new DialogMessage(this, e.Message, MessageBoxCallback) { Caption = "Error!" });
    }
}

private void MessageBoxCallback(MessageBoxResult result)
{
    // Stuff that happens after dialog is closed
}


public class View1 : UserControl
{
    public View1()
    {
        InitializeComponent();
        Messenger.Default.Register<DialogMessage>(this, DialogMessageReceived);
    }

    private void DialogMessageReceived(DialogMessage msg)
    {
            MessageBox.Show(msg.Content, msg.Caption, msg.Button, msg.Icon, msg.DefaultResult, msg.Options);
    }
}