Dynamic Loading of Xaml in WinRt

Tags: WinRt Xaml

I often need to compose some parts of my application at runtime.The UI is one area in WinRt where you can do this. Here it is possible to dynamically load xaml views. This is what you need to do:

async void LoadView()
    // Get the folder containing the views
    StorageFolder folder = 
        await Package.Current.InstalledLocation.GetFolderAsync("Views");
    // Create a stream reader to the file
    StorageFile file = await folder.GetFileAsync("View1.xaml");
    Stream stream = await file.OpenStreamForReadAsync();
    StreamReader reader = new StreamReader(stream);
    // Read the xaml
    String xaml = reader.ReadToEnd();
    // Parse the xaml 
    // (cast to the type of the root element of the xaml file)
    Pageview = XamlReader.Load(xaml) as Page;
    if (view != null)
        // Add the view to the root grid

It is absolutley straightforward. You open the folder, read the file, parse the xaml and add it to your UI.

No Comments

Add a Comment