C# WPF add control to main window at run time

倖福魔咒の 提交于 2019-12-01 02:58:10
Kiril Popov

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

Example :

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

</Grid>
</Window>

Then in the code behind use

RootGrid.Children.Add(img);

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

If your this is indeed a Window, you should know that Window can have only a single child, which you put into Content. If you want several items in Window, usually you put some appropriate container (for example, Grid or StackPanel) as Window's content, and add children to it.

Vlad got the solution. 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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!