Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding WPF UserControl to WPF Window in code

is there a way to add a user control to a WPF Window created in code? I cant find a Children property in the Window Class. In xaml It would look like this:

<Window x:Class="MyWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:MyUserControls="clr-namespace:MyUserControls" 
        Title="" Height="Auto" Width="550" ResizeMode="NoResize">
    <MyUserControls:UC1 x:Name="uc1" />
</Window>

In code I tried something like this:

Window myWindow = new Window;
UC1 uc1 = new UC1;
myWindow.Children.Add(UC1);

Thanks for your help

like image 399
Sebastian Avatar asked May 20 '11 06:05

Sebastian


People also ask

How do I add WPF control to Windows form?

Add a WPF control to a Windows FormOpen Form1 in the Windows Forms Designer. In the Toolbox, find the tab labeled WPFUserControlLibrary WPF User Controls. Drag an instance of UserControl1 onto the form. An ElementHost control is created automatically on the form to host the WPF control.

What is the difference between UserControl and window in WPF?

A window is managed by the OS and is placed on the desktop. A UserControl is managed by wpf and is placed in a Window or in another UserControl. Applcations could be created by have a single Window and displaying lots of UserControls in that Window.

How do we refer to WPF controls in code?

Controls in WPF are accessed by their Name properties. We specify the Name property in the XAML, and then can access the control by that name directly in C# code. Property notes. Name allows controls to interact.

Can we have multiple user controls in WPF?

Adding Multiple Controls to the Content Panel | Basic Library for WPF and Silverlight | ComponentOne. You cannot set the Content property to more than one control at a time.


1 Answers

A Children property is there if you have an ItemsControl, i.e. a control which can have multiple children. A Window is a ContentControl, i.e. it only has one "child", the Content. So the code should be:

myWindow.Content = UC1;
like image 107
Daniel Rose Avatar answered Sep 18 '22 17:09

Daniel Rose