如何使附加财产对子集合的变化做出反应?
我有以下定义附加属性来设置子项边距的类:
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 文件中创建的。顺便说一句,设计器工作正常,并以某种方式正确地为所有子元素设置边距。
I have following class that defines attached property to set children's margin:
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);
}
}
}
The problem is that when CreateThicknesForChildren is invoked no child controls are added to parent yet. How to fix this class so that it will correctly set margin on all child controls?
In my project no controls are dynamically added to parent, they all are created in xaml file. By the way, designer works correctly and somehow correctly sets margin for all children elements.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
注册到面板的Loaded事件怎么样?如果您稍后动态添加项目,它不会有帮助,但对于基本的 95% 来说它会起作用:
How about registering to the Loaded event of the panel? it won't help if you're adding items dynamically later, but for the basic 95% it would work: