技术开发 频道

WPF企业应用基础:布局全接触

  五. StackPanel

  StackPanel就是将子元素按照堆栈的形式一一排列,通过设置面板的Orientation属性设置了两种排列方式:横排(Horizontal默认的)和竖排(Vertical)。纵向的StackPanel默认每个元素宽度与面板一样宽,反之横向亦然。如果包含的元素超过了面板空间,它只会截断多出的内容。 元素的Margin属性用于使元素之间产生一定得间隔,当元素空间大于其内容的空间时,剩余空间将由HorizontalAlignment和VerticalAlignment属性来决定如何分配。其他属性,大家可以看看如下类图:

  要实现的效果如下图(用XAML和C#实现同一效果):

  XAML代码实现:

<Window    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
  
x:Class
="WPFLayoutDemo.StackPanelDEMO"    x:Name="Window"  
Title
="StackPanelDEMO"  
WindowStartupLocation
="CenterScreen"     Width="640" Height="480">  
<StackPanel Margin="0,0,0,0" Background="White" Orientation="Vertical">    
    
<Button Content="Top of Stack"/>  
    
<Button Content="Middle of Stack"/>    
  
<Button Content="Bottom Of Stack"/>    </StackPanel>
</Window>

   C#代码实现:

namespace WPFLayoutDemo{  
  
public partial class StackPanelDEMOCodeBehind
   {      
public StackPanelDEMOCodeBehind()        {          
  this.InitializeComponent();            StackPanel sp
= new StackPanel();  
          
//把sp添加为窗体的子控件            this.Content = sp;          
  sp.Margin
= new Thickness(0, 0, 0, 0);        
   sp.Background
= new SolidColorBrush(Colors.White);          
sp.Orientation
= Orientation.Vertical;      
      
//Button1      
      Button b1
= new Button();            b1.Content = "Top of Stack";            sp.Children.Add(b1);          
//Button2          
  Button b2
= new Button();            b2.Content = "Middle of Stack";            sp.Children.Add(b2);          
  
//Button3          
  Button b3
= new Button();            b3.Content = "Bottom of Stack";            sp.Children.Add(b3);        
}    
}
}

   

0
相关文章