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.
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:
I have highlighted the important bit.