chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
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
using System.Windows;
using System.Windows.Controls;
 
namespace UILib.DpUtil
{
    public class StackPanelHelper
    {
        public static double GetChildSpace(StackPanel sp)
        {
            return (double)sp.GetValue(ChildSpaceProperty);
        }
 
        public static void SetChildSpace(StackPanel sp, double value)
        {
            sp.SetValue(ChildSpaceProperty, value);
        }
 
        public static readonly DependencyProperty ChildSpaceProperty =
            DependencyProperty.RegisterAttached("ChildSpace", typeof(double), typeof(StackPanelHelper),
            new PropertyMetadata(0d, (d, e) =>
            {
                if (!(d is StackPanel sp)) return;
                sp.Loaded += Sp_Loaded;
            }));
 
        private static void Sp_Loaded(object sender, RoutedEventArgs e)
        {
            var sp = sender as StackPanel;
            var children = sp.Children;
            if (sp.Children == null) return;
            double space = GetChildSpace(sp);
            if (sp.Orientation == Orientation.Horizontal)
            {
                for (int i = 0; i < children.Count; i++)
                {
                    if (children[i] is FrameworkElement ui)
                    {
                        ui.Margin = new Thickness(0, 0, (i == children.Count - 1) ? 0 : space, 0);
                    }
                }
            }
            else
            {
                for (int i = 0; i < children.Count; i++)
                {
                    if (children[i] is FrameworkElement ui)
                    {
                        ui.Margin = new Thickness(0, 0, 0, (i == children.Count - 1) ? 0 : space);
                    }
                }
            }
        }
    }
}