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?
You set DockPanel. Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored. If you move DockPanel.
To apply a border to a XAML element, you can place the element within a Border element, The BorderThickness and BorderBrush are two main properties of a Border The BorderBrush property represents the brush that is used to draw the border. The BorderThickness property represents the thickness of the border.
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.
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;
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