2011-10-14 60 views
8

有点荒谬,我无法找到一个简单的答案。 我的目标是在应用程序运行时附加一个新的图像控件。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> 

回答

3

什么是你的情况this?您可以尝试this.Content = image;this.Children.Add(image);

如果您this的确是Window,你应该知道,Window只能有一个孩子,你投入Content。如果您需要Window中的多个项目,通常您会将一些适当的容器(例如,GridStackPanel)作为Window的内容,并向其添加子项。

+0

这是主窗口:http://screensnapr.com/v/OROEvt.png它没有子属性。我需要将它添加到网格中,这是持有按钮和文本框的元素,您在此图片中看到 – Drake

+0

是的,窗口只有内容。你的窗户的内容是什么?你不应该添加到窗口,而是添加到适当的内部容器。这就是布局管理的工作原理:-) – Vlad

10

您应该只有一个根元素在窗口下。使用this.AddChilda添加图像将图像添加为窗口的子项,但您可能还有其他一些子项(例如Grid)。提供一个名称这个孩子(网格中的实例中),然后在代码中的图像后面添加到网格

实施例:

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

</Grid> 
</Window> 

然后,在代码使用

RootGrid.AddChild(img); 
1

后面弗拉德得到了解决方案。我用它:

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); 
相关问题