WPF教程(二十五)WrapPanel

WrapPanel用於一個接一個的排列子控件,以水平或者垂直方向,當空間不足時就會自動切換到下一行。適合於需要水平或者垂直排列控件且能自動換行的情況。

水平方向排列時,每一行所有子控件的高度都被統一成固定的值,這個值由最高的那個決定;每一列垂直方向排列時,所有子控件的寬度都被統一成固定的值,這個值由最寬的那個決定。

我們先來看默認情況下的WrapPanel:

<Window x:Class="WpfTutorialSamples.Panels.WrapPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WrapPanel" Height="300" Width="300">
        <WrapPanel>
                <Button>Test button 1</Button>
                <Button>Test button 2</Button>
                <Button>Test button 3</Button>
                <Button Height="40">Test button 4</Button>
                <Button>Test button 5</Button>
                <Button>Test button 6</Button>
        </WrapPanel>
</Window>
WrapPanel in Horizontal mode

注意我爲第二行中的一個按鈕指定了一個高度,這就使得第二行所有按鈕都被設置成了這個高度。另外,這個面板還做了一件事件:第一行放不下的時候,自動了切換到第二行。

如果你改變窗口大小,譬如縮小窗口,面板立馬自動調整以適應新的尺寸:

WrapPanel in Horizontal mode

這些規則在垂直方向排列時也是一樣的。來看例子:

<Window x:Class="WpfTutorialSamples.Panels.WrapPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WrapPanel" Height="120" Width="300">
        <WrapPanel Orientation="Vertical">
                <Button>Test button 1</Button>
                <Button>Test button 2</Button>
                <Button>Test button 3</Button>
                <Button Width="140">Test button 4</Button>
                <Button>Test button 5</Button>
                <Button>Test button 6</Button>
        </WrapPanel>
</Window>
WrapPanel in Vertical mode
可以看到,垂直排列規則和水平方向的一模一樣。按鈕到達底部後就自動切換到第二列。我給第四個按鈕設置了較寬的寬度,所以第二列都變成了這個寬度。

特別要注意,水平向的WrapPanel自動匹配同一行的高度,而不會匹配寬度;垂直向的WrapPanel自動匹配同一列的寬度,而不會匹配高度。看下面的例子,垂直向的WrapPanel在第四個按鈕同時設置了寬和高:

<Button Width="140" Height="44">Test button 4</Button>
WrapPanel in Vertical mode with specific width/heights

可以看出第五個按鈕只使用了第四個按鈕的寬,並沒有使用高。於是第6個按鈕被擠到了第三列。

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