如何隐藏空的TextBlock?

在下面提供的XAML中,我有时并不具备Phone的价值。 当发生这种情况时,该值将丢失,但TextBlock仍占用面板中的空间。 我想隐藏空的TextBlockStackPanel占用空间。

这是XAML:

 <StackPanel> <TextBlock Text="{Binding Path=FirstName}" /> <TextBlock Text="{Binding Path=LastName}" /> <TextBlock Text="{Binding Path=Phone}" /> <TextBlock Text="{Binding Path=Email}" /> </StackPanel> 

我读过这篇文章 ,但接受的答案不适合我:

 <StackPanel> <TextBlock Text="{Binding Path=FirstName}" /> <TextBlock Text="{Binding Path=LastName}" /> <TextBlock Text="{Binding Path=Phone}"> <TextBlock.Style> <Style TargetType="TextBlock"> <Style.Triggers> <Trigger Property="Text" Value="{x:Null}"> <Setter Property="Visibility" Value="Collapsed" /> </Trigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> <TextBlock Text="{Binding Path=Email}" /> </StackPanel> 

我在某个地方犯了错,还是被接受的答案错了? 我应该怎么做才能达到我的目标?

您可能需要使用:

 <Style TargetType="TextBlock"> <Style.Triggers> <Trigger Property="Text" Value=""> <Setter Property="Visibility" Value="Collapsed" /> </Trigger> </Style.Triggers> </Style> 

或者可能两个:

 <Style TargetType="TextBlock"> <Style.Triggers> <Trigger Property="Text" Value=""> <Setter Property="Visibility" Value="Collapsed" /> </Trigger> <Trigger Property="Text" Value="{x:Null}"> <Setter Property="Visibility" Value="Collapsed" /> </Trigger> </Style.Triggers> </Style> 

而不是只为此引入一种风格,对于这种事情,我倾向于使用一个处理空string或空string的转换器。

 <TextBlock Text="{Binding Foo}" Visibility="{Binding Foo, Converter={StaticResource StringToVisibilityConverter}}" /> 

其中StringToVisibilityConverter是这样定义的:

 [ValueConversion(typeof(string), typeof(Visibility))] public class StringToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (string.IsNullOrEmpty((string)value)) { return Visibility.Collapsed; } else { return Visibility.Visible; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } 

你可以使用DataTrigger

 <TextBlock Text="{Binding Path=Title}"> <TextBlock.Style> <Style TargetType="TextBlock"> <Style.Triggers> <DataTrigger Binding="{Binding Title}" Value="{x:Null}"> <Setter Property="Visibility" Value="Collapsed" /> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock>