Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Add a Border to a StackPanel in Windows 8

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?

like image 529
iTrout Avatar asked Sep 06 '12 01:09

iTrout


People also ask

How to set Border of StackPanel in wpf?

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.

How do you add a border in XAML?

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.

What is a StackPanel 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.


1 Answers

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;
like image 190
Mark Bonafe Avatar answered Oct 05 '22 12:10

Mark Bonafe