我有以下类来定义附加属性以设置子边距:
public class MarginSetter
{
public static Thickness GetMargin(DependencyObject obj)
{
return (Thickness)obj.GetValue(MarginProperty);
}
public static void SetMargin(DependencyObject obj, Thickness value)
{
obj.SetValue(MarginProperty, value);
}
public static readonly DependencyProperty MarginProperty =
DependencyProperty.RegisterAttached("Margin", typeof(Thickness), typeof(MarginSetter), new UIPropertyMetadata(new Thickness(), CreateThicknesForChildren));
public static void CreateThicknesForChildren(object sender, DependencyPropertyChangedEventArgs e)
{
var panel = sender as Panel;
if (panel == null) return;
foreach (var child in panel.Children)
{
var fe = child as FrameworkElement;
if (fe == null) continue;
fe.Margin = MarginSetter.GetMargin(panel);
}
}
}
问题是,当调用CreateThicknesForChildren时,尚未向父级添加子控件。如何修复这个类,以便它能正确设置所有子控件的边距?
在我的项目中,没有控件被动态添加到父级,它们都是在xaml文件中创建的。顺便说一句,设计师正确地工作,并以某种方式正确设置所有子元素的边距。
答案 0 :(得分:2)
如何注册面板的Loaded事件?如果您以后动态添加项目将无济于事,但对于基本的95%,它将起作用:
public static void CreateThicknesForChildren(object sender, DependencyPropertyChangedEventArgs e)
{
var panel = sender as Panel;
panel.Loaded += ...
}