以编程方式将边框添加到Windows 8中的StackPanel

时间:2012-09-06 01:48:02

标签: c# windows-8 code-behind

我试图在StackPanel后面的C#代码中设置以下属性,我需要以编程方式添加:

BorderThickness
BorderBrush

有关如何以编程方式设置这些内容的想法吗?

3 个答案:

答案 0 :(得分:22)

我知道这是一年之后,但我找到了答案,以防有人仍然需要它。

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;

答案 1 :(得分:1)

StackPanel没有BorderThickness或BorderBrush属性。只有背景。如果要设置它们,则需要将StackPanel包装在Border控件中:

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

然后你可以打电话:

StackBorder.BorderThickness = new Thickness(1);
StackBorder.BorderBrush = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Red);

答案 2 :(得分:0)

您无法在StackPanel对象本身上设置边框属性。将StackPanel对象放在Border对象中,并使用以下内容在Border对象上设置BorderThicknessBorderBrush属性:

myBorder.BorderBrush = Brushes.Black;
myBorder.BorderThickness = new Thickness(1);