在下面提供的XAML中,我有时没有电话的价值。当发生这种情况时,该值将丢失,但TextBlock
仍占用面板中的空间。我希望隐藏空TextBlock
以免占用StackPanel
中的空格。
这是XAML:
<StackPanel>
<TextBlock Text="{Binding Path=FirstName}" />
<TextBlock Text="{Binding Path=LastName}" />
<TextBlock Text="{Binding Path=Phone}" />
<TextBlock Text="{Binding Path=Email}" />
</StackPanel>
我已阅读this article,但接受的答案对我不起作用:
<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>
我在某个地方犯了错误,或接受的答案是否错误?我该怎么做才能实现目标?
答案 0 :(得分:78)
您可能需要使用:
<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>
答案 1 :(得分:40)
不是为此引入一种风格,对于这种事情,我倾向于使用一个处理空字符串或空字符串的转换器。
<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();
}
}
答案 2 :(得分:12)
您可以使用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>