How to add a StackPanel in a Button using c# code behind (i.e. convert the following XAML to C# )? There is no Button.Children.Add
...
<Button>
<StackPanel Orientation="Horizontal" Margin="10">
<Image Source="foo.png"/>
</StackPanel>
</Button>
StackPanel is a layout panel that arranges child elements into a single line that can be oriented horizontally or vertically. By default, StackPanel stacks items vertically from top to bottom in the order they are declared. You can set the Orientation property to Horizontal to stack items from left to right.
For example, the order of child elements can affect their size in a DockPanel but not in a StackPanel. This is because StackPanel measures in the direction of stacking at PositiveInfinity, whereas DockPanel measures only the available size. The following example demonstrates this key difference.
A StackPanel allows you to stack elements in a specified direction. By using properties that are defined on StackPanel, content can flow both vertically, which is the default setting, or horizontally.
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;
Set Button.Content
instead of using Button.Children.Add
As a longer explanation:
Content
.Children
- e.g. StackPanel, Grid, WrapPanel, Canvas, etc. As your code already shows, you can set the Content
of a Button to be a Panel - this would ehn allow you to then add multiple child controls. However, really in your example, then there is no need to have the StackPanel as well as the Image. It seems like your StackPanel is only adding Padding - and you could add the Padding to the Image rather than to the StackPanel if you wanted to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With