Search code examples
c#controlsfindname

Can I find a control by name and change a property in a single command?


Can we find a control by name and change a property using a single command in C#? I have this:

TextBlock tb = mainGrid.FindName("FirstNameTextBlock") as TextBlock;
tb.Visibility = Visibility.Collapsed;

Is there a way to do it with a single command? This doesn't work, but something like this:

(TextBlock)mainGrid.FindName("FirstNameTextBlock").Visibility = Visibility.Collapsed;

Solution

  • Yes, there is

    ((TextBlock)mainGrid.FindName("FirstNameTextBlock")).Visibility = Visibility.Collapsed;
    

    You need to cast the object and then modify the properties. The parentheses will take care of this. Without them it assumes whatever FindName returns has a property Visibility and that will be cast into TextBlock.