Search code examples
c#wpfreflectionslidertextblock

C# reference TextBlock by name


I want to reference a C# TextBlock from a XAML page by its name in the form of a string. I want to be able to change the text of a TextBlock after movement on a slider. I can calculate the name of the TextBlock based on that of the Slider.

I am guessing that I should use System.Refelection in some way but I can not figure out how to. I have tried the following:

...
        var slider = sender as Slider;
        var textblock_Name = slider.Name.Replace("Rotation_Slider", "Rotation_TextBlock");
        var type = this.GetType();
        var field = type.GetField("xRotation_TextBlock");
        var textBlock = field.GetValue(this) as TextBlock;
...

But I then get a null-reference exception at the second to last line. I guess that I should probably not be trying to reference a field but I have no idea what it really is.


Solution

  • Try using the FindChild function from this answer here to find the TextBlock: https://stackoverflow.com/a/1759923/2486160