Monday, 18 June 2012

Silverlight ContentMargin Attached Property

Here is a useful Silverlight attached property taken from a Xaml presentation by Miguel Castro.

By setting a property on a Panel it automatically sets the margin property for all its children.

<UserControl x:Class="AttachedProperty.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="clr-namespace:AttachedProperty">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel b:ContentMargin.Margin="10,5,20,15">
<TextBlock HorizontalAlignment="Center" Text="Stack Panel" />
<Button>Button #1</Button>
<Button>Button #2</Button>
<Button>Button #3</Button>
<Button>Button #4</Button>
<Button>Button #5</Button>
<Button>Button #6</Button>
</StackPanel>
</Grid>
</UserControl>


ContentMargin

using System.Windows;
using System.Windows.Controls;

namespace AttachedProperty
{
public static class ContentMargin
{
public static readonly DependencyProperty MarginProperty =
DependencyProperty.RegisterAttached("MarginValue",
typeof (Thickness),
typeof (ContentMargin),
new PropertyMetadata(default(Thickness), OnMarginChanged));

public static Thickness GetMargin(DependencyObject obj)
{
return (Thickness)obj.GetValue(MarginProperty);
}

public static void SetMargin(DependencyObject obj, Thickness value)
{
obj.SetValue(MarginProperty, value);
}

private static void OnMarginChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var element = obj as FrameworkElement;
if (element == null) return;

element.Loaded += element_Loaded;
}

static void element_Loaded(object sender, RoutedEventArgs e)
{
var panel = sender as Panel;
if (panel == null) return;

foreach (var child in panel.Children)
{
var element = child as FrameworkElement;
if (element == null) continue;
Thickness parentMargin = GetMargin(panel);
element.Margin = new Thickness(parentMargin.Left,
parentMargin.Top,
parentMargin.Right,
parentMargin.Bottom);
}
}
}
}


Source:  https://github.com/stevenh77/AttachedProperty

No comments:

Post a Comment