0

I have a XAML page with a DataContext configured for a view model:

<Window.DataContext>
    <current:OrdersViewModel  />
</Window.DataContext>

The constructor for OrdersViewModel attempts to connect to a repository via a factory.

public OrdersViewModel()
{
    using (var repos = RepositoryFactory.Create()) // Throws exception - not configured
    {
        // Get data
    }
}

The factory is configured in the constructor for my App.xaml.cs.

However, when I'm visually editing my main XAML page, it attempts to construct an OrdersViewModel object without calling the App constructor. Thus an exception is thrown from the OrdersViewModel constructor, causing a warning (or sometimes an error) in my XAML editor.

I can get rid of this by simply wrapping my constructor code in a try/catch block.

public OrdersViewModel()
{
    try
    {
        using (var repos = RepositoryFactory.Create()) // Throws exception - not configured
        {
            // Get data
        }
    }
    catch
    {
    }
}

However, this seems inelegant. Exception handling is there for when the code is running, not when it's being edited. And if I get an exception when I'm running, I don't want it ignored like this. And as my program gets more complex, I need more an more of these.

So my question is, is there a way to get the XAML editor to generally ignore exceptions? Or a way to stop it even attempting to create the DataContext object while editing?

(Note: The question is asked here, but there's no entirely general purpose answer.)

Jasper Kent
  • 3,546
  • 15
  • 21
  • I'm not sure this older answer addresses my question any more than the one I referenced. These tell me how to do mocking, which, as my question states, I already do. What I'd like to do is switch off the editor's attempts to create the view-model entirely, or to simply make it ignore exceptions coming from the view-model. – Jasper Kent Mar 28 '20 at 13:32
  • The other question gets you part of the way. The other thing you may need is d:IsDesignTimeCreatable. see https://stackoverflow.com/questions/8472228/how-to-use-ddesigninstance-with-types-that-dont-have-default-constructor – StayOnTarget Apr 22 '20 at 12:18

0 Answers0