Where do I catch Exceptions in MVVM?

前端 未结 1 1603
渐次进展
渐次进展 2021-01-30 17:24

My view model class has a method (not sure if that is good practice or if view models are supposed to be strictly property and property changing mechanisms) that connects to a s

1条回答
  •  有刺的猬
    2021-01-30 18:05

    I've been handling exceptions in my MVVM client by catching them and wrapping them in an ErrorViewModel property of whatever ViewModel caught the exception.

    Let's say a ViewModel A catches the EndpointNotFoundException. To present this error, I wrap the Exception in an ErrorViewModel and assign that to A's Error property.

    The View associated with A contains a ContentControl bound to A's Error property. Meanwhile, I use a DataTemplate to associate an Error View to the ErrorViewModel. In that View, Visibility is determined by whether or not A's Error property contains an exception.

    So A's View contains an error-message View that will only appear when an exception is caught, and can be dismissed by the user (an OK button on the error-message View invokes a command on A that clears A's Error property, thereby changing the error-message View's visibility to Collapsed).

    Thus far, this seems to be a good approach that preserves proper MVVM decoupling.

    Hope that helps. One way or another, honestly, I'd consider System.Windows.MessageBox.Show() in a WPF app as purely a last resort. Why give up rich control over the UI in favor of that old thing? Speaking of which, here's another popup-implementation approach.

    0 讨论(0)
提交回复
热议问题