简体   繁体   中英

Dynamically change the Visibility of a Grid in WPF

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?

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>

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM