C#WPF在运行时将控件添加到主窗口 [英] C# WPF add control to main window at run time

查看:167
本文介绍了C#WPF在运行时将控件添加到主窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在应用程序运行时附加新的图像控件。

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;

我尝试过

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

添加带有表单的元素从未如此困难。
如何简单地将此新元素附加到主窗口(而不是另一个控件),以便它显示出来。

It was never this difficult to add a element with forms. How can I simply attach this new element to the main window (not another control) so that it will show up.

解决了这个问题,我将网格命名为main,从那里我可以访问children属性和添加功能

Solved it, I named the grid main, and from there I was able to access the children attribute and the 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>


推荐答案

窗口下应该只有一个根元素。使用this添加图像。AddChilda将图像添加为window的子级,但是您可能还定义了其他子级(例如Grid)。给这个孩子起个名字(在示例中为网格),然后在后面的代码中将图像添加到网格中。

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

示例:

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

</Grid>
</Window>

然后在使用后的代码中

RootGrid.Children.Add(img);

这篇关于C#WPF在运行时将控件添加到主窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆