Last active
February 25, 2022 18:31
-
-
Save TheVeryStarlk/e1abaa9ab1e08f5742d316653e627c45 to your computer and use it in GitHub Desktop.
An attached property to add spacing inside layout controls like stack-panels in WPF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Windows; | |
using System.Windows.Controls; | |
public class SpacingSetter | |
{ | |
public static readonly DependencyProperty SpacingProperty = | |
DependencyProperty.RegisterAttached("Spacing", typeof(int), typeof(SpacingSetter), | |
new UIPropertyMetadata(0, MarginChanged)); | |
public static int GetSpacing(DependencyObject dependencyObject) | |
{ | |
return (int) dependencyObject.GetValue(SpacingProperty); | |
} | |
public static void SetSpacing(DependencyObject dependencyObject, int value) | |
{ | |
dependencyObject.SetValue(SpacingProperty, value); | |
} | |
private static void MarginChanged(object sender, DependencyPropertyChangedEventArgs eventArgs) | |
{ | |
if (sender is Panel panel) | |
{ | |
panel.Loaded += PanelLoaded; | |
} | |
} | |
private static void PanelLoaded(object sender, RoutedEventArgs eventArgs) | |
{ | |
var panel = (Panel) sender; | |
var firstIterate = true; | |
foreach (var child in panel.Children) | |
{ | |
if (child is FrameworkElement frameworkElement) | |
{ | |
if (!firstIterate) | |
{ | |
frameworkElement.Margin = new Thickness(GetSpacing(panel), 0, 0, 0); | |
} | |
else | |
{ | |
firstIterate = false; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment