XAML C#隐藏网格行

本文关键字:网格 隐藏 XAML | 更新日期: 2023-09-27 18:01:07

我有一个网格,我试图在其中隐藏一行,该行包含一个使用c#作为代码隐藏的文本框我的最终目标是找到一种在隐藏行时在文本框中设置文本的方法。如果文本框的大小小于字体大小,我可能会遇到wpf不允许在文本框中设置文本的问题。这就是我目前所拥有的:

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";
        }
    }
}

根据我所读到的,这应该是可行的。但是,我收到一个关于"RowDefinitions(1("的错误。错误为:"不可调用的成员'Grid.RowDefinitions'不能像方法一样使用。"有什么想法吗?

提前感谢!

XAML C#隐藏网格行

在C#中,索引运算符是[],而不是parens。Parens是方法调用。

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

此外,索引从零开始。1是第二项,而不是第一项。不确定你是否知道,但parens看起来像VB.

这很重要,因为AddressBar只有一行,根本没有行定义;一个有列,另一个有行。不过这很容易解决。

如果你只想隐藏整个网格,那很简单:

AddressBar.Visibility = Visibility.Collapsed;

但您可能希望外部网格中的第一行的Height="Auto",这样它就可以与其内容一起折叠。

你不会遇到文本框大小调整的问题(WPF喜欢隐藏东西(,但在任何情况下,如果你想让它消失,在XAML中将行高设置为Auto,并将textbox的Visibility设置为Collapsed,WPF都会更有意义。当Height="Auto"时,行将根据其内容调整大小。如果内容折叠,则没有行。