Programmatically Add a Border to a StackPanel in Windows 8
Asked Answered
D

3

5

I'm trying to set the following properties in the C# code behind of StackPanel that I need to add programmatically:

BorderThickness
BorderBrush

Any idea on how to set these programmatically?

Dynamometry answered 6/9, 2012 at 1:48 Comment(0)
E
26

I know this is a year later, but I have found an answer in case someone still needs it.

Here is a complete example

// Create a StackPanel and Add children
StackPanel myStackPanel = new StackPanel();
Border myBorder1 = new Border();
myBorder1.Background = Brushes.SkyBlue;
myBorder1.BorderBrush = Brushes.Black;
myBorder1.BorderThickness = new Thickness(1);
TextBlock txt1 = new TextBlock();
txt1.Foreground = Brushes.Black;
txt1.FontSize = 12;
txt1.Text = "Stacked Item #1";
myBorder1.Child = txt1;

Border myBorder2 = new Border();
myBorder2.Background = Brushes.CadetBlue;
myBorder2.Width = 400;
myBorder2.BorderBrush = Brushes.Black;
myBorder2.BorderThickness = new Thickness(1);
TextBlock txt2 = new TextBlock();
txt2.Foreground = Brushes.Black;
txt2.FontSize = 14;
txt2.Text = "Stacked Item #2";
myBorder2.Child = txt2;

// Add the Borders to the StackPanel Children Collection
myStackPanel.Children.Add(myBorder1);
myStackPanel.Children.Add(myBorder2);
mainWindow.Content = myStackPanel;
Emmettemmey answered 5/9, 2013 at 13:23 Comment(0)
F
1

The StackPanel does not have a BorderThickness or BorderBrush properties. Only Background. If you want to set those, you would need to wrap the StackPanel in a Border control:

<Border  x:Name="StackBorder">
<StackPanel>
</Border>

You can then call:

StackBorder.BorderThickness = new Thickness(1);
StackBorder.BorderBrush = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Red);
Frankfort answered 6/9, 2012 at 2:25 Comment(3)
Great idea...the only issue is that I'll have "x" number of StackPanels so I need to create all of them in the code behind. I'm able to programmatically create the Border and StackPanel objects, I just can't seem to find the correct syntax to add the StackPanel to the Border. Any ideas?Dynamometry
@Dynamometry It sounds like you should be using an Itemscontrol rather than creating things in code.Blancablanch
@mydogisbox - I'm using a Callisto Flyout so I need to build it in code. If I could load the Callisto Flyout with XAML, that would be a dream come true!Dynamometry
S
0

You cannot set border properties on the StackPanel object itself. You place the StackPanel object inside a Border object and set the BorderThickness and BorderBrush properties on the Border object with something like:

myBorder.BorderBrush = Brushes.Black;
myBorder.BorderThickness = new Thickness(1);
Studer answered 6/9, 2012 at 2:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.