TOC

This article has been localized into Chinese by the community.

面板控件:

DockPanel控件

DockPanel使得在所有四个方向(顶部、底部、左侧和右侧)都可以很容易地停靠内容。这在很多情况下都是一个很好的选择,其中您希望将窗口划分为特定的区域,尤其是因为默认情况下,DockPanel内的最后一个元素(除非该特性被特别禁用)将自动填充剩余的空间(中心)。

正如我们在WPF中看到的,通过使用面板的附加属性(本例中为DockPanel.Dock属性),您可以开始利用面板的可能性,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="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>

就像早已提到的,我们不给最后一个子控件分配停靠位置,因为它自动居中控件,所以会允许它填满剩余的空间。您还会注意到中心周围的控件只占用了他们需要的空间 - 其他所有内容都留给了中心位置。这就是为啥你看右按钮比左按钮多占用一点空间--只是额外的字符需要更多的像素。

你可能会注意到的最后一件事是空间是如何分配的。 例如,Top按钮没有获得所有顶部空间,因为Left按钮占用了它的一部分。 DockPanel根据它们在标记中的位置来决定优先哪个控件。 在这种情况下,Left按钮优先,因为它首先放在标记中。 幸运的是,这也意味着它很容易改变,正如我们在下一个例子中所看到的那样。我们还可以通过为子控件指定宽度/高度来调整空间:

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

顶部和底部控件现在优先于左右控件,它们都在高度或宽度上占用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>

在这个例子中,我们将两个控件停靠在左侧,两个控件停靠在右侧,同时我们关闭LastChildFill属性。 这使我们在中心留下空的空间,这在某些情况下可能更好。


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!