是否可以轻松地为WPF网格中的行或列指定边距和/或填充?
我当然可以添加额外的列来解决问题,但这似乎是填充/边距的工作(它将提供更简单的XAML)。有人从标准网格派生出来添加此功能吗?
您可以编写自己的GridWithMargin
类,继承自Grid
,并覆盖ArrangeOverride
方法以应用边距
在uwp中(Windows10FallCreatorsUpdate版本及以上版本)
<Grid RowSpacing="3" ColumnSpacing="3">
编辑:
要为任何控件提供边距,可以使用这样的边框包装控件
<!--...-->
<Border Padding="10">
<AnyControl>
<!--...-->
虽然您无法在网格中添加边距或填充,但您可以使用类似框架(或类似容器)的东西,您可以将其应用到。
这样(如果您在按钮上显示或隐藏控件,请单击说),您不需要在可能与其交互的每个控件上添加边距。
可以把它想象成将控件组隔离成单元,然后将样式应用于这些单元。
如前所述,创建一个GridWithMargins类。这是我的工作代码示例
public class GridWithMargins : Grid
{
public Thickness RowMargin { get; set; } = new Thickness(10, 10, 10, 10);
protected override Size ArrangeOverride(Size arrangeSize)
{
var basesize = base.ArrangeOverride(arrangeSize);
foreach (UIElement child in InternalChildren)
{
var pos = GetPosition(child);
pos.X += RowMargin.Left;
pos.Y += RowMargin.Top;
var actual = child.RenderSize;
actual.Width -= (RowMargin.Left + RowMargin.Right);
actual.Height -= (RowMargin.Top + RowMargin.Bottom);
var rec = new Rect(pos, actual);
child.Arrange(rec);
}
return arrangeSize;
}
private Point GetPosition(Visual element)
{
var posTransForm = element.TransformToAncestor(this);
var areaTransForm = posTransForm.Transform(new Point(0, 0));
return areaTransForm;
}
}
用法:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:GridWithMargins ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Rectangle Fill="Red" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
<Rectangle Fill="Green" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
<Rectangle Fill="Blue" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</local:GridWithMargins>
</Grid>
</Window>
我很惊讶我没有发现这个解决方案。
来自Web,像bootstrap这样的框架将使用负边距来拉回行/列。
它可能有点冗长(尽管不是那么糟糕),它确实有效,并且元素的间距和大小均匀。
在下面的示例中,我使用StackPanel
根来演示3个按钮如何使用边距均匀分布。您可以使用其他元素,只需将内部x:类型从按钮更改为元素即可。
这个想法很简单,在外面使用一个网格将元素的边距拉出边界一半的内部网格(使用负边距),使用内部网格以您想要的数量均匀地分隔元素。
更新:用户的一些评论说它不起作用,这是一个快速视频演示:https://youtu.be/rPx2OdtSOYI
<StackPanel>
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type Grid}">
<Setter Property="Margin" Value="-5 0"/>
</Style>
</Grid.Resources>
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Margin" Value="10 0"/>
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="Btn 1" />
<Button Grid.Column="1" Content="Btn 2" />
<Button Grid.Column="2" Content="Btn 3" />
</Grid>
</Grid>
<TextBlock FontWeight="Bold" Margin="0 10">
Test
</TextBlock>
</StackPanel>
我最近在两列网格中遇到了类似的问题,我只需要右列中的元素边距。两列中的所有元素都是TextBlock类型。
<Grid.Resources>
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource OurLabelStyle}">
<Style.Triggers>
<Trigger Property="Grid.Column" Value="1">
<Setter Property="Margin" Value="20,0" />
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
有时简单的方法是最好的。用空格填充你的字符串。如果它只是几个文本框等,这是迄今为止最简单的方法。
您还可以简单地插入具有固定大小的空白列/行。非常简单,您可以轻松更改它。
RowDefinition
和ColumnDefinition
属于ContentElement
类型,Margin
严格来说是FrameworkElement
属性。所以对于你的问题,“这很容易”,答案是肯定的。不,我没有看到任何展示这种功能的布局面板。
您可以按照建议添加额外的行或列。但是你也可以在Grid
元素本身上设置边距,或者在Grid
里面设置任何东西,所以这是你现在最好的解决方法。
在单元格控件外部使用Border
控件并为其定义填充:
<Grid>
<Grid.Resources >
<Style TargetType="Border" >
<Setter Property="Padding" Value="5,5,5,5" />
</Style>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border Grid.Row="0" Grid.Column="0">
<YourGridControls/>
</Border>
<Border Grid.Row="1" Grid.Column="0">
<YourGridControls/>
</Border>
</Grid>
资源:
你可以使用这样的东西:
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Padding" Value="4" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
或者,如果您不需要TemplateBindings:
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border Padding="4">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
以为我会添加自己的解决方案,因为还没有人提到这个。您可以使用样式声明来定位网格中包含的控件,而不是基于Grid设计UserControl。注意为所有元素添加填充/边距而不必为每个元素定义,这是繁琐且劳动密集的。例如,如果你的Grid只包含TextBlocks,你可以这样做:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Margin" Value="10"/>
</Style>
这相当于“细胞填充”。
这并不十分困难。我不能说2009年提出这个问题时有多困难,但就在那时。
请注意,如果在使用此解决方案时直接在网格的子节点上显式设置边距,则该边距将出现在设计器中,但不会出现在运行时。
此属性可以应用于Grid,StackPanel,WrapPanel,UniformGrid或Panel的任何其他后代。它会影响直系儿童。据推测,孩子们想要管理自己内容的布局。
PanelExt.cs
public static class PanelExt
{
public static Thickness? GetChildMargin(Panel obj)
{
return (Thickness?)obj.GetValue(ChildMarginProperty);
}
public static void SetChildMargin(Panel obj, Thickness? value)
{
obj.SetValue(ChildMarginProperty, value);
}
/// <summary>
/// Apply a fixed margin to all direct children of the Panel, overriding all other margins.
/// Panel descendants include Grid, StackPanel, WrapPanel, and UniformGrid
/// </summary>
public static readonly DependencyProperty ChildMarginProperty =
DependencyProperty.RegisterAttached("ChildMargin", typeof(Thickness?), typeof(PanelExt),
new PropertyMetadata(null, ChildMargin_PropertyChanged));
private static void ChildMargin_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var target = d as Panel;
target.Loaded += (s, e2) => ApplyChildMargin(target, (Thickness?)e.NewValue);
ApplyChildMargin(target, (Thickness?)e.NewValue);
}
public static void ApplyChildMargin(Panel panel, Thickness? margin)
{
int count = VisualTreeHelper.GetChildrenCount(panel);
object value = margin.HasValue ? margin.Value : DependencyProperty.UnsetValue;
for (var i = 0; i < count; ++i)
{
var child = VisualTreeHelper.GetChild(panel, i) as FrameworkElement;
if (child != null)
{
child.SetValue(FrameworkElement.MarginProperty, value);
}
}
}
}
演示:
MainWindow.xaml
<Grid
local:PanelExt.ChildMargin="2"
x:Name="MainGrid"
>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Rectangle Width="100" Height="40" Fill="Red" Grid.Row="0" Grid.Column="0" />
<Rectangle Width="100" Height="40" Fill="Green" Grid.Row="1" Grid.Column="0" />
<Rectangle Width="100" Height="40" Fill="Blue" Grid.Row="1" Grid.Column="1" />
<Button Grid.Row="2" Grid.Column="0" Click="NoMarginClick">No Margin</Button>
<Button Grid.Row="2" Grid.Column="1" Click="BigMarginClick">Big Margin</Button>
<ComboBox Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" />
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void NoMarginClick(object sender, RoutedEventArgs e)
{
PanelExt.SetChildMargin(MainGrid, null);
}
private void BigMarginClick(object sender, RoutedEventArgs e)
{
PanelExt.SetChildMargin(MainGrid, new Thickness(20));
}
}
我最近在开发一些软件时遇到了这个问题,它发生在我身上,问为什么?他们为什么要这样做......答案就在我面前。一行数据是一个对象,因此如果我们保持面向对象,那么应该分离特定行的设计(假设您将来需要重新使用行显示)。所以我开始使用数据绑定堆栈面板和自定义控件来进行大多数数据显示。列表偶尔出现,但主要是网格仅用于主页面组织(页眉,菜单区域,内容区域,其他区域)。您的自定义对象可以轻松管理堆栈面板或网格中每一行的任何间距要求(单个网格单元格可以包含整个行对象。这还具有对方向更改,扩展/折叠等作出适当反应的额外好处。
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<custom:MyRowObject Style="YourStyleHereOrGeneralSetter" Grid.Row="0" />
<custom:MyRowObject Style="YourStyleHere" Grid.Row="1" />
</Grid>
要么
<StackPanel>
<custom:MyRowObject Style="YourStyleHere" Grid.Row="0" />
<custom:MyRowObject Style="YourStyleHere" Grid.Row="1" />
</StackPanel>
如果您使用数据绑定,您的自定义控件也将继承DataContext ...我个人最喜欢这种方法的好处。
我现在用我的一个网格做了。
一种可能性是添加固定宽度的行和列作为您要查找的填充/边距。
您可能还会认为您受到容器大小的限制,并且网格将变得与包含元素或其指定的宽度和高度一样大。您可以简单地使用没有设置宽度或高度的列和行。这样他们默认会均匀地分解网格中的总空间。然后它只是在你的网格中垂直和水平居中你的元素的母校。
另一种方法可能是将所有网格元素包装在具有固定大小和边距的单行和列网格的固定中。您的网格包含固定的宽度/高度框,其中包含您的实际元素。