如何在使用後面的c#代碼(即將以下XAML轉換爲C#)的Button中添加StackPanel?沒有Button.Children.Add
...如何在C#代碼後面的按鈕中添加StackPanel
<Button>
<StackPanel Orientation="Horizontal" Margin="10">
<Image Source="foo.png"/>
</StackPanel>
</Button>
如何在使用後面的c#代碼(即將以下XAML轉換爲C#)的Button中添加StackPanel?沒有Button.Children.Add
...如何在C#代碼後面的按鈕中添加StackPanel
<Button>
<StackPanel Orientation="Horizontal" Margin="10">
<Image Source="foo.png"/>
</StackPanel>
</Button>
集Button.Content
,而不是使用Button.Children.Add
至於更詳細的解釋:
Content
。Children
- 例如StackPanel中,網格,WrapPanel,帆布等當你的代碼已經具備了,你可以設置一個按鈕Content
是一個面板 - 這將EHN允許你再添加多個子控件。但是,真的在你的例子中,那麼就沒有必要像StackPanel那樣擁有StackPanel了。看起來你的StackPanel只是添加了Padding,並且你可以添加Padding到圖片,而不是添加到StackPanel。
Image img = new Image();
img.Source = new BitmapImage(new Uri("foo.png"));
StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);
Button btn = new Button();
btn.Content = stackPnl;
使用這樣
<Window.Resources>
<ImageSource x:Key="LeftMenuBackgroundImage">index.jpg</ImageSource>
<ImageBrush x:Key="LeftMenuBackgroundImageBrush"
ImageSource="{DynamicResource LeftMenuBackgroundImage}"/>
</Window.Resources>
和代碼隱藏
Button btn = new Button();
btn.HorizontalContentAlignment = HorizontalAlignment.Stretch;
btn.VerticalContentAlignment = VerticalAlignment.Stretch;
StackPanel stk = new StackPanel();
stk.Orientation = Orientation.Horizontal;
stk.Margin = new Thickness(10, 10, 10, 10);
stk.SetResourceReference(StackPanel.BackgroundProperty, "LeftMenuBackgroundImageBrush");
btn.Content = stk;