本文介绍了在 WPF 中动态更改网格的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有 TextBlock
的 Grid
:
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>
我正在以编程方式设置这个 TextBlock
值:
I am setting this TextBlock
value programatically:
Title.Text = myObject.Title;
现在这里 myObject.Title
有时可能为 Null 或 Empty,那时我需要隐藏整个 Grid
.
Now here myObject.Title
may be Null or Empty sometimes at that time I need to hide this entire Grid
.
如何做到这一点?
推荐答案
在 TextBlock
上设置 x:Name
.然后在 Grid 的样式上应用 dataTriggers
以在 TextBlock 上将 Text
设置为 null 或空字符串时折叠可见性.
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>
这篇关于在 WPF 中动态更改网格的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!