可以在这里看到另一个不错的方法。
您创建用于设置Margin
属性的类:
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<FrameworkElement>())
fe.Margin = GetMargin(panel);
}
}
现在你已经附加了属性行为,这样这样的语法就可以工作了:
<StackPanel local:MarginSetter.Margin="5">
<TextBox Text="hello" />
<Button Content="hello" />
<Button Content="hello" />
</StackPanel>
这是设置Margin
面板的多个子项的最简单和最快的方法,即使它们不是同一类型。(即Button
s、TextBox
es、ComboBox
es 等)