What is the easy way to set spacing between items in StackPanel?

后端 未结 4 795
情书的邮戳
情书的邮戳 2021-02-01 05:50

Is there an easy way to set default space between items inside StackPanel so I\'ll don\'t have to set Margin property on each item?

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-01 06:33

    The accepted answer doesn't work anymore. But I used that answer and the blog the author of that answer (Elad Katz) to make a working code (tested in .Net Core) that I reproduce here:

        public static class EstablecedorMargen { 
    
    
        public static Thickness GetMargen(DependencyObject objeto) => objeto != null ? (Thickness)objeto.GetValue(PropiedadMargen) : new Thickness();
    
        public static void SetMargen(DependencyObject objeto, Thickness value) => objeto?.SetValue(PropiedadMargen, value);
    
        public static readonly DependencyProperty PropiedadMargen 
            = DependencyProperty.RegisterAttached("Margen", typeof(Thickness), typeof(EstablecedorMargen), new UIPropertyMetadata(new Thickness(), Cambió));
    
    
        public static void Cambió(object sender, DependencyPropertyChangedEventArgs e) {
            if (!(sender is Panel panel)) return;
            panel.Loaded += new RoutedEventHandler(EstablecerMargenControlesHijos);
        } 
    
    
        public static void EstablecerMargenControlesHijos(object sender, RoutedEventArgs e) {
    
            if (!(sender is Panel panel)) return;
            foreach (var hijo in panel.Children) {
                if (!(hijo is FrameworkElement feHijo)) continue;
                feHijo.Margin = GetMargen(panel);
            }
    
        } 
    
    
    } 
    

    Then you use:

                 
                

提交回复
热议问题