Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a StackPanel in a Button in C# code behind

Tags:

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>
like image 827
KMC Avatar asked Mar 22 '11 11:03

KMC


People also ask

What is StackPanel?

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.

What is the difference between StackPanel and DockPanel?

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.

What is the use of StackPanel in WPF?

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.


2 Answers

  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;
like image 127
Vitalij B. Avatar answered Sep 29 '22 21:09

Vitalij B.


Set Button.Content instead of using Button.Children.Add

As a longer explanation:

  • Button is a control which "only has 1 child" - its Content.
  • Only very few controls (generally "Panels") can contain a list of zero or more 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.

like image 25
Stuart Avatar answered Sep 29 '22 21:09

Stuart