Handle exceptions with WPF and MVVM

妖精的绣舞 提交于 2019-12-09 19:43:25

问题


I am attempting to build an application using WPF and the MVVM pattern. I have my Views being populated from my ViewModel purely through databinding. I want to have a central place to handle all exceptions which occur in my application so I can notify the user and log the error appropriately.

I know about Dispatcher.UnhandledException but this does not do the job as exception that occur during databinding are logged to the output windows. Because my View is databound to my ViewModel the entire application is pretty much controlled via databinding so I have no way to log my errors.

Is there a way to generically handle the exceptions raised during databinding, without having to put try blocks around all my ViewModel public's?

Example View:

<Window x:Class="Test.TestView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TestView" Height="600" Width="800" 
    WindowStartupLocation="CenterScreen">
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
    </Window.Resources>
    <StackPanel VerticalAlignment="Center">
        <Label Visibility="{Binding DisplayLabel, Converter={StaticResource BooleanToVisibilityConverter}}">My Label</Label>
    </StackPanel>
</Window>

The ViewModel:

public class TestViewModel
{
    public bool DisplayLabel
    {
        get { throw new NotImplementedException(); }
    }
}

It is an internal application so I do not want to use Wer as I have seen previously recommended.


回答1:


The Binding implementation is designed to be fault tolerant and so it catches all the exceptions. What you could do is to activate the following properties in your bindings:

  • ValidatesOnExceptions = true
  • NotifyOnValidationError = true

See also the MSDN.

This causes to raise the attached Error property on the bound control.

However, this infrastructure is designed for validating the user input and show validation messages. I’m not sure if this is what you are doing.



来源:https://stackoverflow.com/questions/1542622/handle-exceptions-with-wpf-and-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!