Przmak
Przmak

Reputation: 53

Accessing xaml grid.column from backend/positioning elements

<Grid x:Name="gv">
     <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
     </Grid.ColumnDefinitions>
     <TextBlock x:Name="aaa" Text="asd" Height="40" Grid.Column="0"/>
</Grid>

So basically I created an element in the backend and want to add it to the gv grid to column 1, how should I do that ?

TextBlock frName = new TextBlock();
frName.Text = "123";
gv.Children.Add(frName);

In xaml it would look like that i guess

<TextBlock Text="123" Height="40" Grid.Column="1"/>

I can't find any property or any note in documentation what is responsible for how to place in desired column.

Ps.

I'm creating Grid Column definitions as well in backend but I found it rly easy how to do it, not sure if I do it in the good way.

Grid tg = new Grid();
GridLength cw = new GridLength(70); 
ColumnDefinition cd;
for (int i = 0; i < 4; i++) {
    cd = new ColumnDefinition();
    cd.Width = cw;
    tg.ColumnDefinitions.Add(cd);
}  

Upvotes: 0

Views: 125

Answers (1)

Rob Caplan - MSFT
Rob Caplan - MSFT

Reputation: 21919

Grid.Row and Grid.Column (and Canvas.Left and Canvas.Top) are attached properties. They are declared by the container class (Grid or Canvas), not by the DependencyObject they are set on. See the Attached properties overview on MSDN.

To set an attached property in code use the SetValue method with the identifier of the property. GetValue will return the property.

frName.SetValue(Grid.ColumnProperty,1);

Your code to create the Grid and its columns is essentially correct. You'll still need to add it to a container in your visual tree similar to how you add frName with gv.Children.Add(frName)

Upvotes: 1

Related Questions