WPF教程(二十七)DockPanel

DockPanel很容易就能把內容停靠到上下左右四個方向上。這個在某些場景顯得非常重要,譬如你想把窗口劃分成指定區域,除非禁用這個特性,否則,DockPanel中最後一個元素將自動填充剩餘的空間。

就像WPF其他面板控件一樣,我們通過使用附加屬性來看看這個面板的優勢。在例子中用了DockPanel.Dock屬性,它決定了子控件將停靠的方向。如果不指定這個屬性,第一個控件就會被停靠到左邊,最後一個填充整個剩餘空間。來看例子:

<Window x:Class="WpfTutorialSamples.Panels.DockPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DockPanel" Height="250" Width="250">
        <DockPanel>
                <Button DockPanel.Dock="Left">Left</Button>
                <Button DockPanel.Dock="Top">Top</Button>
                <Button DockPanel.Dock="Right">Right</Button>
                <Button DockPanel.Dock="Bottom">Bottom</Button>
                <Button>Center</Button>
        </DockPanel>
</Window>
A simple DockPanel
正如提到的那樣,我們沒有給最後一個按鈕指定Dock方向,因爲它能夠自動居中,並且填充剩餘的空間。同時,圍繞中間的所有控件是佔據它們所需要的空間,其他所有的空間都留給了中心位置。右邊的按鈕看起來要比左邊的按鈕大一些,這是因爲右邊Right有5個字母,需要的空間更多。

最後你需要明白的是,整個空間是如何劃分的。例如,頂部按鈕並沒有佔據整個頂部,而是左邊按鈕佔據了頂部的一部分。DockPanel通過查看標記中每個控件的指定位置來決定控件的優先。這上面的例子中,左按鈕是第一個控件,所以它最優先。當然了,這個很容易來更改。我們在下面的例子中,通過指定子控件的寬和高來協調整個空間:

<Window x:Class="WpfTutorialSamples.Panels.DockPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DockPanel" Height="250" Width="250">
        <DockPanel>
                <Button DockPanel.Dock="Top" Height="50">Top</Button>
                <Button DockPanel.Dock="Bottom" Height="50">Bottom</Button>
                <Button DockPanel.Dock="Left" Width="50">Left</Button>
                <Button DockPanel.Dock="Right" Width="50">Right</Button>        
                <Button>Center</Button>
        </DockPanel>
</Window>
A DockPanel where width or heights has been specified for the child controls

現在頂部按鈕和底部按鈕優先於左按鈕和右按鈕,分別被指定了50像素的高或寬。如果你拖大或者縮小窗口,你會發現它們被指定的高和寬不會變化,而中間區域會隨着窗口變化。

LastChildFill

DockPanel默認的是最後一個子控件佔據剩餘的所有空間。這可以通過設置LastChildFill來禁用。下面的例子就禁用了,同時展示了多個控件朝同一方向停靠的效果。

<Window x:Class="WpfTutorialSamples.Panels.DockPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DockPanel" Height="300" Width="300">
        <DockPanel LastChildFill="False">
                <Button DockPanel.Dock="Top" Height="50">Top</Button>
                <Button DockPanel.Dock="Bottom" Height="50">Bottom</Button>
                <Button DockPanel.Dock="Left" Width="50">Left</Button>
                <Button DockPanel.Dock="Left" Width="50">Left</Button>
                <Button DockPanel.Dock="Right" Width="50">Right</Button>
                <Button DockPanel.Dock="Right" Width="50">Right</Button>
        </DockPanel>
</Window>
A DockPanel where the LastChildFill property has been disabled

我們分別將兩個控件停靠到左邊和右邊,同時,我們禁用了LastChildFill屬性。這樣,中間的空間就空出來了,這個在某些場景下很有用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章