简体   繁体   中英

Running project takes too long when MainWindow.xaml is open - WPF

I have started an MVVM application with Entity Framework and WPF. In MainWindow.xaml I wrote this :

<Window x:Class="MVVMAttempt.App.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="400" Width="525"
        DataContext="{StaticResource StudentVM}">

And in App.xaml I wrote this :

    <Application.Resources>
        <vms:StudentVM x:Key="StudentVM" xmlns:vms="clr-namespace:MVVMAttempt.App.ViewModels"/> 
  </Application.Resources>

The project is working correctly. But there is one problem. When MainWindow.xaml is open on Visual Studio, the program starts to run really slowly. Also I get the following error :

Error 1 A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) C:..MVVMAttempt\\MVVMAttempt.App\\App.xaml 3 9 MVVMAttempt.App

How can I fix this? Thanks.

Reason: Designer is trying to initialize static resources and particularly your ViewModel to satisfy bindings. Then you get an exception from Entity Framework context initialization.


How to fix: Use System.ComponentModel.DesignerProperties.IsInDesignTool in your ViewModel to distinguish real life and design time initialization.

if (System.ComponentModel.DesignerProperties.IsInDesignTool)
{
      // Initialize "fake" context here
}
else
{
     // EF context initialization
}


This might seem as an overhead at a firs glance but if you're working with Expression Blend and Visual Studio designer it is really useful to provide some dummy data just to have an idea how your control will "look and feel" in real world.


Another option is to set design-time DataContext in xaml which will do the same trick:

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
d:DataContext="{<Fake/design-time data context binding>}"

According to the error message, there is a problem about accessing to the database. Verify that your connection is ok. Which approach of EF do you use ?

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