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); } } } } } }