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?
-
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
ContentWindow w; object rootElement = w.Content;Edward Tanguay : 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? -
Have you tried this?
MainContent.Children.Add(window.Content);Edward Tanguay : good idea but unfortunately intellisense shows me no "Child" for windowKent Boogaart : that should be window.ContentDrew Noakes : Thanks, I updated the code. Still, you get my point. Did that work?Edward Tanguay : 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? -
The easiest way is to have your XAML/code behind inherit from UserControl - and then everything will just work
Edward Tanguay : bingo, that's exactly what I was trying to do, so simple, thanks!
0 comments:
Post a Comment