在我们的 WPF 4.0 项目(不是 Silverlight)中,我们使用几个自定义附加属性来设置容器的所有子项中的属性值,通常是 aGrid
或 a StackPanel
。我们更喜欢这种策略而不是样式和其他替代方案,因为我们可以在容器的同一个声明中使用更少的代码行。
我们有一个自定义附加属性,用于设置几个典型属性,例如Margin
容器所有子项的属性。我们遇到了其中之一的问题,即HorizontalAlignment
物业。自定义附加属性与其他属性相同:
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,...
。
有任何想法吗?