Access a control created at runtime (WPF)

395 Views Asked by At

I have created a Textblock control at runtime using vb.net but I also need to be able to edit it's properties such as colors and fonts at different times throughout the application.

This is the program how I am creating the control.

Public Sub New()


    InitializeComponent()


        Dim TextBlockPlayerName As New TextBlock

        TextBlockPlayerName.Name = "TextBlockPlayerName"
        TextBlockPlayerName.Text = "Some text"

        Grid.SetRow(TextBlockPlayerName, 1)
        Grid.SetColumn(TextBlockPlayerName, 2)

        GridVotes.Children.Add(TextBlockPlayerName)

End Sub

The code works and the textblock shows up correctly however I get errors whenever I try to do anything to the control throughout the rest of the program.

I have tried using

FindName("TextBlockPlayerName")

and

GridVotes.FindName("TextBlockPlayerName")

However I always get System.NullReferenceException exception saying 'Object reference not set to an instance of an object' when I try to access it as simply as this

Dim PlayerName As TextBlock = FindName("TextBlockPlayerName")

MessageBox.Show(PlayerName.Name)

Everything works fine if I do this to a control I created in Design view but not if I create it with the code. Not sure if it has anything to do with the fact it is in the 'New' Sub and after the InitialzeComponent but I cannot do it beforehand.

1

There are 1 best solutions below

2
On BEST ANSWER

A control that is created in the designer is added to the namescope for the window/usercontrol/template you have created it in.

When you add a control in code behind, it is not added to this scope. Why not? It is relatively expensive to do a look up. By creating it in code you get a reference to the new control anyway. It is expected that you will just keep the reference for when you need it.

There is msdn documentation on namescope that will help you achieve what you need:

Adding Objects to Runtime Object Trees

The moment that XAML is parsed represents the moment in time that a WPF XAML namescope is created and defined. If you add an object to an object tree at a point in time after the XAML that produced that tree was parsed, a Name or x:Name value on the new object does not automatically update the information in a XAML namescope. To add a name for an object into a WPF XAML namescope after XAML is loaded, must call the appropriate implementation of RegisterName on the object that defines the XAML namescope, which is typically the XAML page root. If the name is not registered, the added object cannot be referenced by name through methods such as FindName, and you cannot use that name for animation targeting.

http://msdn.microsoft.com/en-us/library/ms746659%28v=vs.110%29.aspx

I have highlighted the important bit.