-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLayoutSetter.cs
More file actions
69 lines (56 loc) · 2.28 KB
/
LayoutSetter.cs
File metadata and controls
69 lines (56 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System.Windows;
using System.Windows.Controls;
//http://blogs.microsoft.co.il/eladkatz/2011/05/29/what-is-the-easiest-way-to-set-spacing-between-items-in-stackpanel/
namespace YourNamespace
{
public class LayoutSetter
{
#region Margin
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(LayoutSetter), new UIPropertyMetadata(new Thickness(), PropertyChangedCallback));
#endregion
#region VerticalAlignment
public static VerticalAlignment GetVerticalAlignment(DependencyObject obj)
{
return (VerticalAlignment)obj.GetValue(VerticalAlignmentProperty);
}
public static void SetVerticalAlignment(DependencyObject obj, VerticalAlignment value)
{
obj.SetValue(VerticalAlignmentProperty, value);
}
public static readonly DependencyProperty VerticalAlignmentProperty =
DependencyProperty.RegisterAttached("VerticalAlignment", typeof(VerticalAlignment), typeof(LayoutSetter), new UIPropertyMetadata(VerticalAlignment.Top, PropertyChangedCallback));
#endregion
// Add any other FrameworkElement properties you may need
public static void PropertyChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
{
// Make sure this is put on a panel (ex: Grid)
var panel = sender as Panel;
if (panel == null) return;
panel.Loaded += panel_Loaded;
}
static void panel_Loaded(object sender, RoutedEventArgs e)
{
var panel = sender as Panel;
panel.Loaded -= panel_Loaded; // avoids issues with potential reloading, from code-behind for example
foreach (var child in panel.Children)
{
var fe = child as FrameworkElement;
if (fe == null) continue;
//http://stackoverflow.com/a/19798648/3283203
if (fe.ReadLocalValue(FrameworkElement.MarginProperty) == DependencyProperty.UnsetValue)
fe.Margin = LayoutSetter.GetMargin(panel);
if (fe.ReadLocalValue(FrameworkElement.VerticalAlignmentProperty) == DependencyProperty.UnsetValue)
fe.VerticalAlignment = LayoutSetter.GetVerticalAlignment(panel);
}
}
}
}