Dynamically change the Visibility of a Grid in WPF

2019-02-20 16:03发布

问题:

I have a Grid with TextBlock in it:

<Grid x:Name="GridLayout" Margin="4,0,4,1" Grid.Row="2" Background="#accdd7">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <TextBlock Name="Title" 
               Grid.Row="0"
               HorizontalAlignment="Stretch"
               Padding="10,2,10,2"
               Style="{StaticResource PromptTextStyle}" />
</Grid>

I am setting this TextBlock value programatically:

Title.Text = myObject.Title;

Now here myObject.Title may be Null or Empty sometimes at that time I need to hide this entire Grid.

How to acheive this?

回答1:

Set x:Name on TextBlock. Then apply dataTriggers on Grid's style to collapsed the visibility when Text is set to null or empty string on TextBlock.

    <Grid xmlns:sys="clr-namespace:System;assembly=mscorlib"
          x:Name="GridLayout" Margin="4,0,4,1" Grid.Row="2" Background="#accdd7">
        <Grid.RowDefinitions>
           <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TextBlock x:Name="Title" 
                   Grid.Row="0"
                   HorizontalAlignment="Stretch"
                   Padding="10,2,10,2"
                   Style="{StaticResource PromptTextStyle}"/>
        <Grid.Style>
            <Style TargetType="Grid">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Text, ElementName=Title}"
                                 Value="{x:Null}">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Text, ElementName=Title}" 
                                 Value="{x:Static sys:String.Empty}">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Style>
    </Grid>


回答2:

Try this, in code behind

if(string.IsNullOrEmpty(myObject.Title))
{
GridLayout.Visibility = Visibility.Collapsed;
Title.Text=string.Empty;
}
else
{
Title.Text = myObject.Title;
GridLayout.Visibility = Visibility.Visible;
}


回答3:

May the answer above is for Windows Phone 7

I solved it myself.

Here is how i did.

In the Xaml make the Visibility of the grid item to be collapsed by default, and now in code check the myObject.Title is null or not. if not null then set grid visibilty to visible.