C # WPF add control to main window at runtime

Itโ€™s a little funny that I canโ€™t find a simple answer to this question. My goal is to attach a new image control while the application is running.

img = new System.Windows.Controls.Image(); img.Margin = new Thickness(200, 10, 0, 0); img.Width = 32; img.Height = 32; img.Source = etc; 

Ive tried

 this.AddChild(img);// says must be a single element this.AddLogicalChild(img);// does nothing this.AddVisualChild(img);// does nothing 

It has never been so difficult to add an element with forms. How can I just attach this new element to the main window (not to another control) so that it displays.

Having solved it, I named the main grid, and from there I was able to access the children attribute and add function

 main.children.add(img); <Window x:Class="Crysis_Menu.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded" AllowsTransparency="False" Background="White" Foreground="{x:Null}" WindowStyle="SingleBorderWindow"> <Grid Name="main"> <Button Content="Run" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="btnRun" VerticalAlignment="Top" Width="151" Click="btnRun_Click" /> <TextBox Height="259" HorizontalAlignment="Left" Margin="12,40,0,0" Name="tbStatus" VerticalAlignment="Top" Width="151" /> </Grid> </Window> 
+10
c # wpf children
source share
3 answers

You should have only one root element under the window. Adding an image using this.AddChilda adds the image as a child of the window, but you probably have another specific child (like Grid). Give a name to this child (in this Grid example), and then in the code add the image to the Grid.

Example:

 <Window> <Grid x:Name="RootGrid"> </Grid> </Window> 

Then in the code behind use

 RootGrid.Children.Add(img); 
+11
source share

What is this in your case? You can try this.Content = image; or this.Children.Add(image);

If your this really a Window , you should know that a Window can only have one child that you put in Content . If you need several elements in the Window , usually you put the contents of the container (for example, Grid or StackPanel ) in the appropriate container and add children to it.

+4
source share

Vlad got a decision. I used it:

 var grid = this.Content as Grid; // or any controls Label lblMessage = new Label { Content = "I am a label", Margin = new Thickness(86, 269, 0, 0) }; grid.Children.Add(lblMessage); 
+1
source share

All Articles