2012-01-15 38 views
1

我定義我的完整視圖模型使用XAML:將xaml文件的內容分配給App.ViewModel屬性?

<local:TestViewModel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:local="clr-namespace:icColors" 
        SampleProperty="Sample Text Property Value"> 

    <local:TestViewModel.Questions> 
    .... 
    </local:TestViewModel.Questions> 
</local:TestViewModel> 

在運行時如何解析這個XAML,並設置爲我的應用程序,App.TestViewModel的屬性?

回答

1

您可以使用XAMLReader類在運行時解析XAML。只需使用XamlReader.Load方法解析您的XAML,然後分配它(記住投射結果)。以下是一些示例代碼:

System.Windows.Resources.StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(uri); 

if ((streamInfo != null) && (streamInfo.Stream != null)) 
{ 
    using (System.IO.StreamReader reader = new System.IO.StreamReader(streamInfo.Stream)) 
    { 
     TestViewModel vm = System.Windows.Markup.XamlReader.Load(reader.ReadToEnd()) as TestViewModel; 
    } 
} 
相關問題