Nelson T Joseph Nelson T Joseph - 1 year ago 182
C# Question

Dynamically Add Grid UWP

I want to add a grid and its contents on runtime. The Grid is as follows. How can I add this from Code Behind?

<Grid Width="200" Height="50" Margin="0,50,0,0">
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<CheckBox Grid.Column="0" Name="chkBox" MinWidth="32" HorizontalAlignment="Left" Background="Transparent"/>
<TextBlock Grid.Column="1" Text="Name" FontSize="16" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBox Grid.Column="2" Name="txtBx" FontSize="16" HorizontalAlignment="Right" VerticalAlignment="Center"/>

Answer Source
  Grid grid = new Grid();
            grid.Width = 200;
            grid.Height = 50;
            grid.Margin = new Thickness(0, 50, 0, 0);
            ColumnDefinition col1 = new ColumnDefinition();
            ColumnDefinition col2 = new ColumnDefinition();
            ColumnDefinition col3 = new ColumnDefinition();
            col1.Width = new GridLength(0, GridUnitType.Auto);
            col2.Width = new GridLength(0, GridUnitType.Auto);
            col3.Width = new GridLength(1, GridUnitType.Star);
            CheckBox cbox = new CheckBox();
            cbox.MinWidth = 32;
            cbox.HorizontalAlignment = HorizontalAlignment.Left;
            cbox.Background = new SolidColorBrush(Windows.UI.Colors.Transparent);
            TextBlock tblock = new TextBlock();
            tblock.FontSize = 16;
            tblock.HorizontalAlignment = HorizontalAlignment.Left;
            tblock.VerticalAlignment = VerticalAlignment.Center;
            tblock.Text = "text";
            TextBox tbox = new TextBox();
            tbox.FontSize = 16;
            tbox.HorizontalAlignment = HorizontalAlignment.Left;
            tbox.VerticalAlignment = VerticalAlignment.Center;
            Grid.SetColumn(cbox, 0);
            Grid.SetColumn(tblock, 1);
            Grid.SetColumn(tbox, 2);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download