Loading XAML at runtime?
Asked Answered
O

6

51

First some background: I'm working on an application and I'm trying to follow MVVM conventions writing it. One thing I'd like to do is to be able to give the application different "skins" to my application. The same application, but show one "skin" for one client and a different "skin" for another.

And so my questions are:
1. Is it possible to load a xaml file at run time and "assign" it to my app?
2. Can the xaml file be an external file residing in a different folder?
3. Can the application switch to another xaml file easily, or only at startup time?

So where should I start looking at for information on this? Which WPF methods, if they exist, handle this functionality?

Thanks!

Edit: the type of "skinning" I'm wanting to do is more than just changing the look of my controls. The idea is having a completely different UI. Different buttons, different layouts. Kinda like how one version of the app would be fully featured for experts and another version would be simplified for beginners.

Ooze answered 26/5, 2009 at 13:53 Comment(0)
D
17

I think this is fairly simple with the XamlReader, give this a shot, didn't try it myself, but I think it should work.

https://learn.microsoft.com/en-us/archive/blogs/ashish/dynamically-loading-xaml

Demonolater answered 26/5, 2009 at 14:59 Comment(1)
Link no longer works, try this: learn.microsoft.com/en-us/archive/blogs/ashish/…Housel
E
38

As Jakob Christensen noted, you can load any XAML you want using XamlReader.Load. This doesn't apply only for styles, but UIElements as well. You just load the XAML like:

UIElement rootElement;
FileStream s = new FileStream(fileName, FileMode.Open);
rootElement = (UIElement)XamlReader.Load(s);
s.Close();

Then you can set it as the contents of the suitable element, e.g. for

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Foo Bar">
    <Grid x:Name="layoutGrid">
        <!-- any static elements you might have -->
    </Grid>
</Window>

you could add the rootElement in the grid with:

layoutGrid.Children.Add(rootElement);
layoutGrid.SetColumn(rootElement, COLUMN);
layoutGrid.SetRow(rootElement, ROW);

You'll naturally also have to connect any events for elements inside the rootElement manually in the code-behind. As an example, assuming your rootElement contains a Canvas with a bunch of Paths, you can assign the Paths' MouseLeftButtonDown event like this:

Canvas canvas = (Canvas)LogicalTreeHelper.FindLogicalNode(rootElement, "canvas1");
foreach (UIElement ui in LogicalTreeHelper.GetChildren(canvas)) {
    System.Windows.Shapes.Path path = ui as System.Windows.Shapes.Path;
    if (path != null) {
        path.MouseLeftButtonDown += this.LeftButtonDown;
    }
}

I've not tried switching XAML files on the fly, so I cannot say if that'll really work or not.

Enedina answered 26/5, 2009 at 15:15 Comment(5)
Hi TomiJ! This seems to be about what I'm looking for. The only bit I'm missing is how to handle .xaml files that are part of the solution. How would I go and load them?Ooze
In the application I'm working on, I just keep the XAML files in the solution and set their Build Action to "none", and have Visual Studio copy the files to the output directory if newer. The first code snippet above will then be used to load them.Enedina
Here's what I was looking for, loading a xaml as a resource msdn.microsoft.com/en-us/library/aa970494.aspxOoze
Do you know if this approach is supposed to support bindings? I've tried it and can't even get it to throw an exception, so I suspect nothing is making the binding actually happen in my case.Prussian
@NeilBarnwell, I rather suspect it doesn't support bindings, so you'd have to create them manually after loading the XAML. (Disclaimer: Just my guess.)Enedina
D
17

I think this is fairly simple with the XamlReader, give this a shot, didn't try it myself, but I think it should work.

https://learn.microsoft.com/en-us/archive/blogs/ashish/dynamically-loading-xaml

Demonolater answered 26/5, 2009 at 14:59 Comment(1)
Link no longer works, try this: learn.microsoft.com/en-us/archive/blogs/ashish/…Housel
P
8

I made simple markup extension, which loads xaml:

public class DynamicXamlLoader : MarkupExtension
{
    public DynamicXamlLoader() { }

    public DynamicXamlLoader(string xamlFileName)
    {
        XamlFileName = xamlFileName;
    }

    public string XamlFileName { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var provideValue = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
        if (provideValue == null || provideValue.TargetObject == null) return null;

        // get target
        var targetObject = provideValue.TargetObject as UIElement;
        if (targetObject == null) return null;

        // get xaml file
        var xamlFile = new DirectoryInfo(Directory.GetCurrentDirectory())
            .GetFiles(XamlFileName ?? GenerateXamlName(targetObject), SearchOption.AllDirectories)
            .FirstOrDefault();

        if (xamlFile == null) return null;

        // load xaml
        using (var reader = new StreamReader(xamlFile.FullName))
            return XamlReader.Load(reader.BaseStream) as UIElement;
    }

    private static string GenerateXamlName(UIElement targetObject)
    {
        return string.Concat(targetObject.GetType().Name, ".xaml");
    }
}

Usage:

This find and load MyFirstView.xaml file

<ContentControl Content="{wpf:DynamicXamlLoader XamlFileName=MyFirstView.xaml}" />

And this fill whole UserControl (find and load MySecondView.xaml file)

<UserControl x:Class="MySecondView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Content="{wpf:DynamicXamlLoader}" />
Prendergast answered 30/8, 2013 at 10:55 Comment(0)
H
5

You can load any XAML that you want using XamlReader.Load.

If you style all your controls in your application and define those styles in your applications resource dictionary you can load new styles defined in XAML somewhere else using XamlReader.Load and replace parts of your resource dictionary with the loaded XAML. Your controls will change appearance accordingly.

Hardison answered 26/5, 2009 at 14:41 Comment(0)
F
4

I have done loading XAML at runtime, here is a short example

Grid grd = new Grid();
var grdEncoding = new ASCIIEncoding();
var grdBytes = grdEncoding.GetBytes(myXAML);
grd = (Grid)XamlReader.Load(new MemoryStream(grdBytes));
Grid.SetColumn(grd, 0);
Grid.SetRow(grd, 0);
parentGrid.Children.Add(grd);

private String myXAML = @" <Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Margin='30 10 30 65' VerticalAlignment='Bottom'>" +
                    "<Label Content='Date: 1-Feb-2013' FontFamily='Arial' FontSize='12' Foreground='#666666' HorizontalAlignment='Left'/>" +
                    "<Label Content='4'  FontFamily='Arial' FontSize='12' Foreground='#666666' HorizontalAlignment='Center'/>" +
                    "<Label Content='Hello World'  FontFamily='Arial' FontSize='12' Foreground='#666666' HorizontalAlignment='Right'/>" +
                "</Grid>";
Fundamentalism answered 30/5, 2013 at 9:30 Comment(0)
C
1

As it's already mentioned in other answers, you can use XamlReader.Load.

If you are looking for a more straightforward example, here is an example showing how easily you can create a control from a string variable containing the XAML:

public T LoadXaml<T>(string xaml)
{
    using (var stringReader = new System.IO.StringReader(xaml))
    using (var xmlReader = System.Xml.XmlReader.Create(stringReader))
        return (T)System.Windows.Markup.XamlReader.Load(xmlReader);
}

And as the usage:

var xaml = "<TextBox xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation\'>" +
            "Lorm ipsum dolor sit amet." +
            "</TextBox>";
var textBox = LoadXaml<System.Windows.Controls.TextBox>(xaml);
Coimbatore answered 2/8, 2018 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.