user5890660 user5890660 - 4 months ago 72
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:

XAML:

Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>

<Button x:Name="Button1"
Grid.Row="2"
Grid.Column="1"
Width="100"
Height="50"
Click="OnClick"
Content="Hide Middle Row"/>

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

<TextBlock x:Name="Block1"
FontSize="16"
Grid.ColumnSpan="3"
HorizontalAlignment="Center"
TextAlignment="Center"/>

</Grid>
</Grid>


C#:

namespace rowCollapseTest
{

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

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

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.