How to change the properties of a dynamically created object in WPF?

Kathryn Porter 41 Reputation points
2021-10-11T13:10:05.49+00:00

Hi

I have recently dynamically created a grid but am unsure of how to access it to change its properties (i.e. its background color). this is on WPF so control doesn't seem to work. I was just wondering if I perhaps did something wrong or am not understanding the fundamentals of creating dynamic objects. I'm fairly new to WPF so apologies if this is something very basic.

Here is the code I am using to create the grid;

For a = 0 To noOfPanels
For i = 0 To (panelno - 1)
Dim Snake_block As New Grid
Snake_block.Name = "snakeBlock" & i & "_" & a
Snake_block.Height = Panel_Height
Snake_block.Width = Panel_Height
Snake_block.Background = New SolidColorBrush(Color.FromRgb(20, 224, 13))
Snake_block.HorizontalAlignment = Windows.HorizontalAlignment.Left
Snake_block.VerticalAlignment = VerticalAlignment.Top

            Dim margin_thickness As New Thickness
            margin_thickness.Left = (panelSpaceSize * (i + 1)) + (Panel_Height * i)

            margin_thickness.Top = (top_space * (a + 1)) + (Panel_Height * a)
            If i = 19 Then
                margin_thickness.Right = panelSpaceSize
            End If

            margin_thickness.Bottom = 0

            Snake_block.Margin = margin_thickness
            Grid.SetColumn(Snake_block, 1)
            myGrid.Children.Add(Snake_block)
        Next
    Next

Thank you.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,814 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 119.2K Reputation points
    2021-10-11T18:08:45.197+00:00

    According to https://social.msdn.microsoft.com/Forums/vstudio/en-US/c8de53a0-07ca-4eaa-83d3-ffa58a2a01b5, you can find the elements by name using LogicalTreeHelper. For example:

    Dim g as Grid = CType(LogicalTreeHelper.FindLogicalNode( myGrid, "snakeBlock3_4" ), Grid)
    g.Background = Brushes.Red
    

    You can also define a bi-dimensional array of blocks; something like this:

    Dim blocks(noOfPanels, panelno - 1) As Grid
    . . .
    Dim Snake_block As New Grid
    blocks(a, i) = Snake_block
    

    Then you can use expressions like blocks(4, 3) or blocks(j, k). Using arrays is probably more performant.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.