Mega Code Archive

 
Categories / VB.Net Tutorial / WPF
 

Change the margins of an element that is within a Grid by XAML and programmatic code

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     x:Class="Grid_Convert_Value_Csharp.Window1"     Title="Dynamically Change Margin Property Sample">   <DockPanel Background="White">     <TextBlock DockPanel.Dock="Top" FontSize="24" FontWeight="Bold">Grid Margin Property Sample</TextBlock>         <Border Border.Background="LightSteelBlue" Border.BorderThickness="2" Border.BorderBrush="Black" DockPanel.Dock="Top">             <Grid Name="grid1" Height="400">               <Grid.ColumnDefinitions>                 <ColumnDefinition/>               </Grid.ColumnDefinitions>               <Grid.RowDefinitions>                 <RowDefinition/>               </Grid.RowDefinitions>                 <TextBlock Name="text1" HorizontalAlignment="Center" Grid.Column="0" Grid.Row="0">Some Text.</TextBlock>           </Grid>         </Border>         <Grid HorizontalAlignment="Center" Width="300" DockPanel.Dock="Top">         <Grid.RowDefinitions>           <RowDefinition/>         </Grid.RowDefinitions>         <Grid.ColumnDefinitions>           <ColumnDefinition Width="Auto"/>           <ColumnDefinition Width="*"/>         </Grid.ColumnDefinitions>               <ListBox Grid.Row="0" Grid.Column="1" Width="50" Height="50" VerticalAlignment="Top" SelectionChanged="ChangeMargin">                   <ListBoxItem>10</ListBoxItem>                   <ListBoxItem>20</ListBoxItem>                   <ListBoxItem>30</ListBoxItem>                   <ListBoxItem>40</ListBoxItem>                   <ListBoxItem>50</ListBoxItem>                   <ListBoxItem>60</ListBoxItem>                   <ListBoxItem>70</ListBoxItem>                   <ListBoxItem>80</ListBoxItem>                   <ListBoxItem>90</ListBoxItem>                   <ListBoxItem>100</ListBoxItem>               </ListBox>           </Grid>       </DockPanel>         </Window> //File:Window.xaml.vb Imports System Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Documents Imports System.Windows.Navigation Namespace Grid_Convert_Value_Csharp   Public Partial Class Window1     Inherits Window     Public Sub ChangeMargin(sender As Object, args As SelectionChangedEventArgs)       Dim li As ListBoxItem = TryCast(TryCast(sender, ListBox).SelectedItem, ListBoxItem)       Dim myThicknessConverter As New ThicknessConverter()       Dim th1 As Thickness = CType(myThicknessConverter.ConvertFromString(li.Content.ToString()), Thickness)       text1.Margin = th1       Dim st1 As [String] = DirectCast(myThicknessConverter.ConvertToString(text1.Margin), [String])       Console.WriteLine("Margin: " & st1)     End Sub   End Class End Namespace