C# 在 Windows 8 中以编程方式向 StackPanel 添加边框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12291927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:45:49  来源:igfitidea点击:

Programmatically Add a Border to a StackPanel in Windows 8

c#windows-8code-behind

提问by iTrout

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

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

BorderThickness
BorderBrush

Any idea on how to set these programmatically?

关于如何以编程方式设置这些的任何想法?

回答by akton

You cannot set border properties on the StackPanelobject itself. You place the StackPanel object inside a Borderobject and set the BorderThicknessand BorderBrushproperties on the Border object with something like:

您不能在StackPanel对象本身上设置边框属性。您将 StackPanel 对象放在Border对象内,BorderThicknessBorderBrush使用以下内容在 Border 对象上设置和属性:

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

回答by Jeff Brand

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:

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

<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);

回答by Mark Bonafe

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;