我目前正在關注來自Microsoft虛擬學院的windows phone教程,其中一個挑戰是使用在項目中創建並在運行時加載的設計xaml viewmodel 。在運行時加載xaml viewmodel與windows phone
經過幾個小時的研究,我認爲是時候訴諸於計算器,因爲我沒有得到任何地方。我已經閱讀了很多文章,沒有人給我一個正確的答案,所以我有幾個問題:
- 如何解決我的錯誤?
- 如何在運行時以編程方式加載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;
}
雖然我可能在錯誤的位置調用它,現在,我發現了以下錯誤:
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in System.Windows.ni.dll
{System.Windows.Markup.XamlParseException: Unknown parser error: Scanner 2147500037. [Line: 5 Position: 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()}
Unknown parser error: Scanner 2147500037. [Line: 5 Position: 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,但大多數都涉及到裝載用戶控件,等等。但沒有一個視圖模型
任何幫助將不勝感激。
謝謝。
嗨巴赫蒂,非常感謝!問題排序!我最終將XamlReader放入了app.xaml.cs中,但它感覺不太對勁!你知道更好的方法嗎? – Thierry