using System.Windows; using System.Windows.Controls; namespace HMI.UI.DpUtil { public class GridHelper { public static double GetSpace(DependencyObject obj) { return (double)obj.GetValue(SpaceProperty); } public static void SetSpace(DependencyObject obj, double value) { obj.SetValue(SpaceProperty, value); } public static readonly DependencyProperty SpaceProperty = DependencyProperty.RegisterAttached("Space", typeof(double), typeof(Grid), new PropertyMetadata(0d, OnShowBorderChanged)); private static void OnShowBorderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is Grid grid) { if (e.Property == SpaceProperty) { grid.Loaded += GridSpaceOnLoaded; return; } } } private static void GridSpaceOnLoaded(object sender, RoutedEventArgs e) { if (!(sender is Grid grid)) return; RefreshGridSpace(grid); grid.Loaded -= GridSpaceOnLoaded; } public static void RefreshGridSpace(Grid grid) { double space = GetSpace(grid); if (space <= 0) { return; } var rowCount = grid.RowDefinitions.Count; var columnCount = grid.ColumnDefinitions.Count; int totalCount = rowCount * columnCount; if (grid.Children == null) return; foreach (FrameworkElement cell in grid.Children) { int row = Grid.GetRow(cell); int col = Grid.GetColumn(cell); int rowSpan = Grid.GetRowSpan(cell); int colSpan = Grid.GetColumnSpan(cell); cell.Margin = new Thickness(space, space, (col + colSpan) == columnCount ? space : 0, (row + rowSpan) == rowCount ? space : 0); } } } }