sb
alielie
2025-03-03 f90615921589586c1f9efde22620b45243d94657
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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);
            }
        }
 
    }
}