如何使附加属性对子集合更改做出反应
本文关键字:子集合 何使附 属性 | 更新日期: 2023-09-27 17:48:54
>我有以下类,它定义了附加属性来设置子边距:
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 文件中创建的。顺便说一下,设计器工作正常,并且以某种方式正确设置了所有子元素的边距。
如何注册面板的加载事件? 如果您稍后动态添加项目,这将无济于事,但对于基本的 95% 它会起作用:
public static void CreateThicknesForChildren(object sender, DependencyPropertyChangedEventArgs e)
{
var panel = sender as Panel;
panel.Loaded += ...
}