Page 1 of 1

Creating a DataTemplate programatically

Posted: 24 Feb 2017, 19:36
by KeldorKatarn
Is there any way to create a DataTemplate in code? The usually recommended way in WPF is using XamlReader.Parse() which is not available in NOESIS. Any alternatives?

Re: Creating a DataTemplate programatically

Posted: 24 Feb 2017, 21:42
by jsantos
Right now, we don't expose that functionality directly. But you can achieve something similar by installing custom providers:
    private static void RegisterProviders()
    {
        Provider p = new Provider()
        {
            XamlProvider = NoesisXamlProvider.instance,
            TextureProvider = NoesisTextureProvider.instance,
            FontProvider = NoesisFontProvider.instance
        };

        Noesis.GUI.SetResourceProvider(p);
    }
Your can implement a provider that justs return a stream to the given string.
public class MyXamlProvider: XamlProvider
{
    public override Stream LoadXaml(string uri)
    {
	byte[] byteArray = Encoding.UTF8.GetBytes(uri);
	return new MemoryStream(byteArray);
    }
}
Yes, it is a bit hacky. We will add direct support for this.

Re: Creating a DataTemplate programatically

Posted: 25 Feb 2017, 02:12
by sfernandez
Couldn't you just create the classes?
var text = new TextBlock();
text.SetBinding(TextBlock.TextProperty, new Binding("Name"));
var border = new Border { Background = Brushes.Silver, Child = text };
var dataTemplate = new DataTemplate { VisualTree = border };

Re: Creating a DataTemplate programatically

Posted: 25 Feb 2017, 04:42
by KeldorKatarn
From what I know that doesn't work for DataTemplates sicne they're not visual elements but templates for elements. There used to be a WPF API
with a class called FrameworkElementFactory or something like that. Instead of the elements themselves you needed to create factories for them so once
the data template gets instatiated, the elements can get created.
But first of all you don't suppor tthat class either, and 2nd neither should you since Microsoft marked it as deprecated. The only way in WPF to do this
is to parse a XAML string.

See http://stackoverflow.com/questions/5471 ... ode-behind

Regarding the Stream thing... what good is a stream exactly? I need a DataTemplate return value, not a memory stream.