C# WPF运行时添加控件到主窗口

15

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

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

以前添加表单元素从未这么困难。如何将这个新元素简单地附加到主窗口(而不是其他控件),以便它会显示出来。

问题已解决,我将网格命名为"main",然后就可以访问其子属性和添加函数了。

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>
3个回答

15

在window下应该只有一个根元素。使用this.AddChild将图像添加为窗口的子级,但您可能已经定义了其他子级(Grid 例如)。给这个子级(例如Grid)命名,然后在代码后台将图像添加到Grid中。

例如:

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

</Grid>
</Window>

然后在代码后端使用

RootGrid.Children.Add(img);

6
在您的情况下,“this”是什么?您可以尝试“this.Content = image;”或“this.Children.Add(image);”。如果您的“this”确实是一个“Window”,则应该知道“Window”只能有一个子级,而将其放入“Content”中。如果您想在“Window”中放置多个项目,通常会将一些适当的容器(例如“Grid”或“StackPanel”)作为窗口的内容,并将子项添加到其中。

这是主窗口:http://screensnapr.com/v/OROEvt.png 它没有子属性。我需要将它添加到网格中,该元素包含您在此图片中看到的按钮和文本框。 - Drake
是的,窗口只有内容。那么你的窗口内容是什么呢?你应该将内容添加到适当的内部容器中,而不是直接添加到窗口中。这就是布局管理的工作原理 :-) - Vlad

2

Vlad找到了解决方案。我使用了它:

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接