有點荒謬,我無法找到一個簡單的答案。 我的目標是在應用程序運行時附加一個新的圖像控件。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