tags:

views:

141

answers:

3

I have a StackPanel called "MainContent".

I can dynamically fill it with UIElements like this:

TextBlock textBlock = new TextBlock();
textBlock.Text = String.Format("This is text");
textBlock.Background = new SolidColorBrush(Colors.Beige);
MainContent.Children.Add(textBlock);

Button button = new Button();
button.Content = "This is a button";
MainContent.Children.Add(button);

But I want to go beyond that and fill it with a XAML/Codebehind pair (e.g. Page or Window):

Type type = this.GetType();
Assembly assembly = type.Assembly;
Window window = (Window)assembly.CreateInstance(String.Format("{0}.{1}", type.Namespace, "Test1"));
MainContent.Children.Add(window);

But the above code complains that I can't add a "Window to a Visual". I can do window.ShowDialog() of course but then it is external to my main window. I want the Test1 window to be embedded in my application.

How can I do this?

Added: The main question is: how can I get Window (or Page) to act as a UIElement so I can embed them dynamically in StackPanels, etc. Currently looking at XamlLoader, anyone experienced with that?

+1  A: 

I don't know if it's possible. But instead of filling the panel with a Window, why not fill it with the root element of the window instead. You'll get all the content and value of the window without the unneeded chrome.

Update: you can grab the root element of a window via the Dependency Property Content

    Window w;
    object rootElement = w.Content;
Scott Weinstein
Sounds great, how to I get the "root element of the window dynamically", e.g. window.LayoutRoot, window.RootElement, window.Children[0]... what is the syntax?
Edward Tanguay
MainContent.Children.Add((UIElement)rootElement) compiles but gets a runtime error. That's the problem, how can I cast the Window into a UIElement?
Edward Tanguay
A: 

Have you tried this?

MainContent.Children.Add(window.Content);
Drew Noakes
good idea but unfortunately intellisense shows me no "Child" for window
Edward Tanguay
that should be window.Content
Kent Boogaart
Thanks, I updated the code. Still, you get my point. Did that work?
Drew Noakes
but MainContent.Children.Add() needs a UIElement and window.Child is not a UIElement. I can cast it as such and it compiles but gets a rutime error. How can I get window to successfully act as a UIElement?
Edward Tanguay
+1  A: 

The easiest way is to have your XAML/code behind inherit from UserControl - and then everything will just work

Nir
bingo, that's exactly what I was trying to do, so simple, thanks!
Edward Tanguay