【问题标题】:DesignTime only error when trying to load an xml to a dataset尝试将 xml 加载到数据集时仅出现 DesignTime 错误
【发布时间】:2013-06-22 16:21:36
【问题描述】:

我创建了一个产生此错误的简单 WPFApplication 项目

这是确切的错误:

找不到文件 'C:\Users\Andrei\AppData\Local\Microsoft\VisualStudio\11.0\Designer\ShadowCache\dj2szrx3.5nm\e412xqna.uj1\Locality.xml'。 E:\BugDemo2\BugDemo2\MainWindow.xaml 7 9 BugDemo2

MainWindow.xaml

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" x:Class="MainWindow"
    Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <!--This is the line that Visual Studio says it produce the error -->
        <local:MainWindowViewModel x:Key="MainWindowViewModelDataSource" d:IsDataSource="True"/>
    </Window.Resources>
    <Grid DataContext="{Binding Source={StaticResource MainWindowViewModelDataSource}}"/>
</Window>

MainWindowViewModel.vb

Imports System.Data
Imports System.IO
Public Class MainWindowViewModel
    Shared ds As New DataSet("Locality")

    Public Sub New()
        MySub()
    End Sub

    Sub MySub()
        'this is the line that actually gives the error
        ds.ReadXml(
           Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location) &
           "\Locality.xml")
        MsgBox(ds.Tables.Count)
    End Sub

End Class

我在 MainWindow.xaml.vb 后面的代码中没有任何内容

Class MainWindow
End Class

程序完全按照它应该做的事情,它正确地将 Locality.xml 加载到数据集并显示其中有多少表。 如果我将 ds 变量移动到另一个模块或另一个类中,作为共享属性,我会得到

Object reference not set to an instance of an object

也仅作为设计时错误。

我知道 Visual Studio 不知道 Locality.xml 是否存在,但它为什么会关心以及如何让这个错误消失?

【问题讨论】:

  • 那么错误中这个文件的路径是正确的?

标签: wpf vb.net visual-studio-2012 blend design-time


【解决方案1】:

使用保护代码,并且更易于调试,因为您可以在执行ReadXml之前检查变量:

Sub MySub()
    Dim path As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location) &
       "\Locality.xml"
    If IO.File.Exists(path) Then
      ds.ReadXml(path)
      MsgBox(ds.Tables.Count)
    End If
End Sub

【讨论】:

  • 这显然奏效了,我不敢相信我一直在做 If IsNothing(ds) then 之类的事情......但我没想到要检查实际文件。我觉得有点愚蠢,但至少我有一个解决方案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 2018-08-15
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 2023-03-31
  • 2021-06-13
相关资源
最近更新 更多