user5890660 user5890660 - 1 year ago 321
C# Question

XAML C# Hide Grid Row

I have a grid where I am trying to hide a row which contains a text box using c# as my code behind. My end goal is to find a way to set text in the text box while the row is hidden hidden. I may run into problems where wpf does not allow text to be set in a textbox if the size of the textbox is smaller than the font size. This is what I have so far:


<RowDefinition Height="100"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="100"/>

<Button x:Name="Button1"
Content="Hide Middle Row"/>

<Grid x:Name="AddressBar" Grid.Row="1" Grid.Column="2">
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>

<TextBlock x:Name="Block1"



namespace rowCollapseTest

public partial class MainWindow : Window
public MainWindow()

private void OnClick(object sender, RoutedEventArgs e)
AddressBar.RowDefinitions(1).Height = new GridLength(0);
AddressBar.Visibility = Visibility.Collapsed;
Block1.Text = "This is a test";

From what I have read, this should work. However, I am receiving an error concerning "RowDefinitions(1)". The error reads: "Non-invocable member 'Grid.RowDefinitions' cannot be used like a method." Any ideas?

Thanks in advance!

Answer Source

In C#, the indexing operator is [], not parens. Parens is method call.

AddressBar.RowDefinitions[1].Height = new GridLength(0);

Also, indexes start at zero. 1 is the second item, not the first. Not sure if you knew that, but the parens look like VB.

That matters a lot because AddressBar has only one row, and NO row definitions at all; that one has columns, the other one has rows. That's easy to fix though.

If you just want to hide that whole grid, that's a snap:

AddressBar.Visibility = Visibility.Collapsed;

But you'll probably want the first row in the outer grid to have Height="Auto", so it collapses along with its content.

You won't run into that sizing problem with the textbox (WPF loves hiding things), but in any case it would make more WPF sense to set the row height to Auto in the XAML and set the TextBox's Visibility to Collapsed when you want it to be gone. With Height="Auto", the row will size itself to its contents. If the contents collapse, no row.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download