Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically create border for cells of a Grid

Tags:

c#

wpf

xaml

<Grid x:Name="LayoutGrid" Visibility="Visible" Background="Transparent" Canvas.Left="20">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="200"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="50" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="600" />
                </Grid.RowDefinitions>
                <Border Grid.Row="0" Grid.Column="0"  BorderBrush="Black"  BorderThickness="1" />
                <Border Grid.Row="2" Grid.Column="0"  BorderBrush="Black"  BorderThickness="1" />
</Grid>

In this XAML code I am putting a border in two cells of a grid. I need to change the design and do the same thing in C# instead. I know how to instantiate a Border in C# and assign it properties, but how do I associate each Border object with the correct cell in the Grid? (named here 'LayoutGrid' ). In other words how do I do in C# what the element is doing in the XAML code above?

like image 428
user2192101 Avatar asked Oct 16 '25 04:10

user2192101


1 Answers

Assuming that myBorder is already child of LayoutGrid

var myBorder = new Border();
LayoutGrid.Children.Add(myBorder)

you either use Grid static methods

Grid.SetColumn(myBorder, 0);
Grid.SetRow(myBorder, 1);

or set DependencyProperty it directly

myBorder.SetValue(Grid.ColumnProperty, 0);
myBorder.SetValue(Grid.RowProperty, 1);
like image 117
dkozl Avatar answered Oct 18 '25 20:10

dkozl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!