技术开发 频道

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

  七. DockPanel

  DockPanel定义一个区域,在此区域中,您可以使子元素通过描点的形式排列。停靠面板其实就是在WinForm类似于Dock属性的元素。DockPanel会对每个子元素进行排序,并停靠在面板的一侧,多个停靠在同侧的元素则按顺序排序,最后一个元素填充这个Panel(这个需要设置LastChildFill属性为 True)。对于在DockPanel中的元素的停靠属性可以通过Panel.Dock的附加属性来设置.

  要实现的效果如下图(用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.DockPanelDEMO"    x:Name="Window"  
Title
="DockPanelDEMO"    WindowStartupLocation="CenterScreen"    Width="640" Height="480">  
<DockPanel Width="Auto" Height="Auto" LastChildFill="True">      
<Rectangle Fill="Beige" Stroke="BlanchedAlmond" Height="180" DockPanel.Dock="Top"/>    
<Rectangle Fill="Azure" Stroke="Orange"
/>  
</DockPanel>
</Window>

   C#代码实现:

namespace WPFLayoutDemo{  
  
public partial class DockPanelDEMOCodeBehind  
{    
  
public DockPanelDEMOCodeBehind()        {          
  this.InitializeComponent();            DockPanel dp
= new DockPanel();            dp.LastChildFill = true;          
dp.Width
= Double.NaN;  
  
//这个就相当于在XAML中设置Width="Auto"          
  dp.Height
= Double.NaN;  
//这个就相当于在XAML中设置Height="Auto"          
//把dp添加为窗体的子控件        
this.Content
= dp;          
  
//添加Rectangles        
Rectangle rTop
= new Rectangle();          
rTop.Fill
= new SolidColorBrush(Colors.BlanchedAlmond);            rTop.Stroke = new SolidColorBrush(Colors.BlanchedAlmond);            rTop.Height = 180;          
dp.Children.Add(rTop);            rTop.SetValue(DockPanel.DockProperty,Dock.Top);            Rectangle rFill
= new Rectangle();            rFill.Fill = new SolidColorBrush(Colors.Azure);          
  rFill.Stroke
= new SolidColorBrush(Colors.Azure);          
  dp.Children.Add(rFill);  
      }  
  }
}

    八. Grid

  Grid和其他各个Panel比较起来,功能最多也最为复杂,它由列元素集和行元素集合两种元素组成。而放置在Grid面板中的控件元素都必须显示采用附加属性语法定义其放置所在的行和列,否则元素均默认放置在第0行第0列。由于Grid的组成并非简单的添加属性标记来区分行列,这也使得用户在实际应用中可以具体到某一单元格中,所以布局起来就很精细了。

  Grid的列宽与行高可采用固定、自动、按比列三种方式定义

<Grid>
  
<Grid.RowDefinitions>    
    
<RowDefinition Height="Auto" />  
      
<RowDefinition Height="Auto" />  
      
<RowDefinition Height="*" />
      
<RowDefinition Height="40" />  
  
</Grid.RowDefinitions>
  
<Grid.ColumnDefinitions>  
      
<ColumnDefinition Width="Auto" />  
    
<ColumnDefinition Width="300" />  
  
</Grid.ColumnDefinitions>
</Grid>

     

0
相关文章