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

  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:

  • 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.


Use like this

<Window.Resources>   
    <ImageSource x:Key="LeftMenuBackgroundImage">index.jpg</ImageSource>
    <ImageBrush x:Key="LeftMenuBackgroundImageBrush" 
     ImageSource="{DynamicResource LeftMenuBackgroundImage}"/> 
</Window.Resources>

and in Codebehind

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;

Tags:

C#

Wpf

Xaml

Button