【发布时间】:2013-07-11 12:54:20
【问题描述】:
在我们的 WPF 4.0 项目(不是 Silverlight)中,我们使用多个自定义附加属性来设置容器的所有子项中的属性值,通常是 Grid 或 StackPanel。我们更喜欢这种策略而不是样式和其他替代方案,因为我们可以在容器的同一个声明中使用更少的代码行。
我们有一个自定义附加属性,用于设置几个典型属性,例如容器所有子项的Margin 属性。我们遇到了其中一个问题,HorizontalAlignmentproperty。自定义附加属性与其他属性相同:
public class HorizontalAlignmentSetter
{
public static readonly DependencyProperty HorizontalAlignmentProperty = DependencyProperty.RegisterAttached("HorizontalAlignment", typeof(HorizontalAlignment), typeof(HorizontalAlignmentSetter), new UIPropertyMetadata(HorizontalAlignment.Left, HorizontalAlignmentChanged));
public static HorizontalAlignment GetHorizontalAlignment(DependencyObject obj) { return (HorizontalAlignment)obj.GetValue(HorizontalAlignmentProperty); }
public static void SetHorizontalAlignment(DependencyObject obj, HorizontalAlignment value) { obj.SetValue(HorizontalAlignmentProperty, value); }
private static void HorizontalAlignmentChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var panel = sender as Panel;
if (panel == null) return;
panel.Loaded += PanelLoaded;
}
static void PanelLoaded(object sender, RoutedEventArgs e)
{
var panel = (Panel)sender;
foreach (var child in panel.Children)
{
var fe = child as FrameworkElement;
if (fe == null) continue;
fe.HorizontalAlignment = GetHorizontalAlignment(panel);
}
}
}
XAML 中的用法也一样:
<Grid util:HorizontalAlignmentSetter.HorizontalAlignment="Left">
<Label .../>
<TextBox .../>
</Grid>
未调用附加属性,因此未在Grid 的子项中设置属性值。调试应用程序时,我们看到调用了静态属性声明 (public static readonly DependencyProperty HorizontalAlignmentProperty = DependencyProperty.RegisterAttached...),但没有调用其他代码,例如 SetHorizontalAlignment(DependencyObject obj... 和回调 private static void HorizontalAlignmentChanged(object sender,...。
有什么想法吗?
【问题讨论】:
标签: wpf wpf-4.0 attached-properties