2011-10-14 66 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); 
相關問題