我目前正在参加Microsoft Virtual Academy的Windows Phone教程,其中一个挑战是在项目中使用设计XAML视图模型,并在运行时加载。
研究了数小时后,我认为该求助Stack Overflow了,因为我没有得到任何进展。我阅读了许多文章,但没有给出正确答案,所以我有几个问题:
- 如何修复我的错误?
- 如何通过编程方式在运行时加载XAML模型视图?
- 如何使用XAML在运行时加载XAML模型视图?
- 在哪里调用运行时加载XAML的方法?
样本数据文件SoundViewModelSampleData.xaml看起来像这样:
<vm:SoundViewModel
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Soundboard.ViewModels"
xmlns:mo="clr-namespace:Soundboard.Models">
<vm:SoundViewModel.Animals>
<vm:SoundGroupViewModel Title="Animals Sample">
<vm:SoundGroupViewModel.Items>
<mo:SoundDataModel Title="Animals 1" FilePath="Animals.wav" />
</vm:SoundGroupViewModel.Items>
</vm:SoundGroupViewModel>
</vm:SoundViewModel.Animals>
<vm:SoundViewModel.Cartoons>
<vm:SoundGroupViewModel Title="Cartoons Sample">
<vm:SoundGroupViewModel.Items>
<mo:SoundDataModel Title="Cartoons 1" FilePath="Cartoons.wav" />
<mo:SoundDataModel Title="Cartoons 2" FilePath="Cartoons.wav" />
</vm:SoundGroupViewModel.Items>
</vm:SoundGroupViewModel>
</vm:SoundViewModel.Cartoons>
</vm:SoundViewModel>
我找到的最简单的通过编程加载它的代码是:
string path = @".\SampleData\SoundViewModelSampleData.xaml";
using (System.IO.StreamReader reader = new System.IO.StreamReader(path))
{
SoundViewModel vm = XamlReader.Load(reader.ReadToEnd()) as SoundViewModel;
}
虽然我可能现在从错误的位置调用它,但我遇到了以下错误:
类型为 'System.Windows.Markup.XamlParseException' 的第一次机会异常发生在 System.Windows.ni.dll 中
{System.Windows.Markup.XamlParseException: 未知的解析器错误: Scanner 2147500037。[行: 5 位置: 14] at MS.Internal.XcpImports.CreateFromXaml(String xamlString, Boolean createNamescope, Boolean requireDefaultNamespace, Boolean allowEventHandlers, Boolean expandTemplatesDuringParse, Boolean trimDeclaredEncoding) at System.Windows.Markup.XamlReader.Load(String xaml) at Soundboard.ViewModels.SoundViewModel.LoadData()}
未知的解析器错误: Scanner 2147500037。[行: 5 位置: 14]
假设我可以解决这个错误,这将解决我的问题1和2(修复错误并以编程方式加载数据)。
你能找出是什么导致了这个问题吗?
如上所述,我可能在错误的位置加载它,即在应用程序加载时创建 ViewModel 内部。
namespace Soundboard.ViewModels
{
public class SoundViewModel
{
public SoundGroupViewModel Animals { get; set; }
public SoundGroupViewModel Cartoons { get; set; }
public bool IsDataLoaded { get; set; }
public void LoadData()
{
string path = @".\SampleData\SoundViewModelSampleData.xaml";
using (System.IO.StreamReader reader = new System.IO.StreamReader(path))
{
SoundViewModel vm = System.Windows.Markup.XamlReader.Load(reader.ReadToEnd()) as SoundViewModel;
}
IsDataLoaded = true;
}
}
在我的app.xaml.cs中,我有以下内容:
public static SoundViewModel SoundViewModel
{
get
{
if (_soundViewModel == null)
{
_soundViewModel = new SoundViewModel();
_soundViewModel.LoadData();
}
return _soundViewModel;
}
}
现在我该如何只使用XAML来实现运行时,并使用d:datacontext进行设计时呢?
我已经阅读了一些文章,但它们都是关于WPF的,大多数与加载用户控件等有关,但没有涉及到ViewModel。
非常感谢您的帮助。
谢谢。