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

101 views Asked by At

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;
1

There are 1 answers

2
Sami Kuhmonen On BEST ANSWER

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.