【发布时间】:2010-01-15 18:58:45
【问题描述】:
我正在开发一个内容为网格的 WPF 控件。我对 WPF 比较陌生,所以我想知道以下是否是解决此问题的正确方法。
我在网格中放置了两个标签,都在同一列但相邻的行:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="UntitledProject8.Window1"
x:Name="Window"
Title="Window1"
Width="200" Height="200">
<Grid x:Name="LayoutRoot">
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="100"/>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="1.23" FontSize="18" HorizontalAlignment="Center" VerticalAlignment="Bottom"/>
<Label Grid.Row="1" Content="45" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Top"/>
</Grid>
我设置标签的垂直对齐方式,使第 0 行的标签与底部对齐,第 1 行的标签与顶部对齐。
现在,这接近我想要的,但我需要第 1 行标签的实际文本更接近第 0 行标签的文本。为此,我将第 1 行中标签的边距设置为负值:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="UntitledProject8.Window1"
x:Name="Window"
Title="Window1"
Width="200" Height="200">
<Grid x:Name="LayoutRoot">
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="100"/>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="1.23" FontSize="18" HorizontalAlignment="Center" VerticalAlignment="Bottom"/>
<Label Grid.Row="1" Content="45" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,-20,0,0"/>
</Grid>
这是正确的做法吗?当然,我上面的示例很简单,但随着网格内容的增长和变得更加复杂(例如包括其他布局容器),为控制边距设置不同的值是使相邻单元格更近或更远的正确方法吗?
我只是有点担心,因为我正在尽力避免硬编码任何类型的“设计器”值,就像我在使用 WinForms 时所做的那样(例如设置位置的精确坐标和大小的值),并且希望让布局管理器来处理它。但是,设置边距似乎是唯一的方法。
感谢您的帮助:)
【问题讨论】: