当MainWindow.xaml打开时,运行项目需要太长时间 - WPF

时间:2014-07-07 07:11:40

标签: c# wpf xaml mvvm

我已经使用Entity Framework和WPF启动了MVVM应用程序。在MainWindow.xaml中我写了这个:

<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}">

在App.xaml中我写了这个:

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

该项目正常运作。但是有一个问题。在Visual Studio上打开MainWindow.xaml时,程序开始运行得非常慢。我也收到以下错误:

  

错误1发生与网络相关或特定于实例的错误   建立与SQL Server的连接。找不到服务器或   无法访问。验证实例名称是否正确   SQL Server配置为允许远程连接。 (提供者:SQL   网络接口,错误:26 - 查找服务器/实例时出错   指定)C:.. MVVMAttempt \ MVVMAttempt.App \ App.xaml 3 9 MVVMAttempt.App

我该如何解决这个问题?感谢。

2 个答案:

答案 0 :(得分:1)

原因: Designer正在尝试初始化静态资源,特别是ViewModel以满足绑定。然后,您从 Entity Framework 上下文初始化中获得异常。

<小时/>

如何修复:在System.ComponentModel.DesignerProperties.IsInDesignTool中使用ViewModel来区分现实生活和初始设计时间。

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


这可能看起来是第一眼的开销,但如果您正在使用 Expression Blend Visual Studio设计器,那么提供它真的很有用一些虚拟数据只是为了了解你的控件在现实世界中的“外观和感觉”。

<小时/> 另一种选择是在DataContext中设置设计时xaml,它将执行相同的操作:

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

答案 1 :(得分:0)

根据错误消息,存在访问数据库的问题。验证您的连接是否正常。您使用EF的哪种方法?