I have a set of Key/Value pairs I want to display on a WPF Window. I\'m using a grid to lay them out like so:
Another nice approach can be seen here.
You create class for setting Margin
property:
public class MarginSetter
{
public static Thickness GetMargin(DependencyObject obj) => (Thickness)obj.GetValue(MarginProperty);
public static void SetMargin(DependencyObject obj, Thickness value) => obj.SetValue(MarginProperty, value);
// Using a DependencyProperty as the backing store for Margin. This enables animation, styling, binding, etc…
public static readonly DependencyProperty MarginProperty =
DependencyProperty.RegisterAttached(nameof(FrameworkElement.Margin), typeof(Thickness),
typeof(MarginSetter), new UIPropertyMetadata(new Thickness(), MarginChangedCallback));
public static void MarginChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
{
// Make sure this is put on a panel
var panel = sender as Panel;
if (panel == null) return;
panel.Loaded += Panel_Loaded;
}
private static void Panel_Loaded(object sender, EventArgs e)
{
var panel = sender as Panel;
// Go over the children and set margin for them:
foreach (FrameworkElement fe in panel.Children.OfType())
fe.Margin = GetMargin(panel);
}
}
Now you have attached property behavior, so that syntax like this would work:
This is the easiest & fastest way to set Margin
to several children of a panel, even if they are not of the same type. (I.e. Button
s, TextBox
es, ComboBox
es, etc.)