【问题标题】:Running project takes too long when MainWindow.xaml is open - WPFMainWindow.xaml 打开时运行项目花费的时间太长 - WPF
【发布时间】:2014-07-07 07:11:40
【问题描述】:

我已经使用实体框架和 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

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

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

    原因:设计师正在尝试初始化静态资源,尤其是您的ViewModel 以满足绑定。然后你会从 Entity Framework 上下文初始化中得到一个异常。


    如何解决:在您的ViewModel 中使用System.ComponentModel.DesignerProperties.IsInDesignTool 来区分现实生活和设计时初始化。

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


    乍一看,这似乎是一种开销,但如果您正在使用 Expression Blend 和 Visual Studio 设计器,提供一些虚拟数据只是为了了解您的控件在现实世界中的“外观和感觉”。


    另一种选择是在xaml 中设置设计时DataContext,这将起到同样的作用:
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    d:DataContext="{<Fake/design-time data context binding>}"
    

    【讨论】:

    • 有点晚了,什么是假上下文?
    • @jason 例如,来自资源的特定 ViewModel 具有存根数据,这将满足绑定,因此您可以查看包含数据的视图。
    【解决方案2】:

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

    【讨论】:

    • 我使用的是代码优先。我可以进行 CRUD 操作,所以虽然出现错误,但我可以对数据库进行读写操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    相关资源
    最近更新 更多