Change the Margin Property

How to: Change the Margin Property

This example shows how to change the Margin property of a child element that is in a Grid. The example represents positioning values as content in a ListBoxItem. The values are later converted into instances of Thickness, which is a required value for Margin. The value is then converted back to a string and displayed as a TextBlock.


The following example creates a ListBox element that has ten selectable items. The SelectionChanged event triggers the ChangeMargin custom method, which the subsequent code example defines.

In the Extensible Application Markup Language (XAML) example, each ListBoxItem represents a Thickness value, which is used to describe the uniform margins of an element. However, before you can use a ListBoxItem to represent an instance of Thickness, you must first convert it to the correct data type. The subsequent code example shows the conversion.

<ListBox VerticalAlignment="Top" Grid.Row="0" Grid.Column="1" Width="50" Height="50" SelectionChanged="ChangeMargin">

When a user changes the ListBox selection, the change invokes the ChangeMargin custom method. This method passes the ListBoxItem to a ThicknessConverter object, which converts the ListBoxItem Content to an instance of Thickness. (Notice that this value has already been converted to a string by using the ToString method.) This value is then passed back as the Margin of the text1 object, dynamically changing its position.

public void ChangeMargin(object sender, SelectionChangedEventArgs args)
    ListBoxItem li = ((sender as ListBox).SelectedItem as ListBoxItem);
    ThicknessConverter myThicknessConverter = new ThicknessConverter();
    Thickness th1 = (Thickness)myThicknessConverter.ConvertFromString(li.Content.ToString());
    text1.Margin = th1;
    String st1 = (String)myThicknessConverter.ConvertToString(text1.Margin);
    gridVal.Text = "The Margin property is set to " + st1 +".";

For the complete sample, see Changing Margins in a Grid Sample.

See Also

Community Additions

© 2016 Microsoft