尝试将xml加载到数据集时,仅设计时出错

时间:2013-06-22 16:21:36

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

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

这是确切的错误:

  

找不到文件   'C:\用户\安德烈\应用程序数据\本地\微软\ VisualStudio的\ 11.0 \设计\ 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,但为什么它关心,如何让这个错误消失呢?

1 个答案:

答案 0 :(得分: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