在我們的WPF 4.0項目(不是Silverlight)中,我們使用幾個自定義附加屬性來設置容器的所有子項中的屬性值,通常爲Grid
或StackPanel
。我們更喜歡這種策略,而不是樣式和其他替代方案,因爲我們可以在容器的同一聲明中使用更少的代碼行。WPF附加屬性不適用於在子元素中設置HorizontalAlignment
我們有一個自定義附加屬性,用於設置幾個典型屬性,如容器的所有子項的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,...
。
任何想法?
太棒了!有用! –