有点荒谬,我无法找到一个简单的答案。 我的目标是在应用程序运行时附加一个新的图像控件。C#WPF在运行时向主窗口添加控件
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.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>
这是主窗口:http://screensnapr.com/v/OROEvt.png它没有子属性。我需要将它添加到网格中,这是持有按钮和文本框的元素,您在此图片中看到 – Drake
是的,窗口只有内容。你的窗户的内容是什么?你不应该添加到窗口,而是添加到适当的内部容器。这就是布局管理的工作原理:-) – Vlad