0

How to make a textBlock auto hide if empty in windows phone 7 app (C#, silverlight, xaml)?

I know there's a similar question for WPF but it seems not applicable in silverlight.

4

1 回答 1

8

您可以使用转换器:

<TextBlock Visibility="{Binding YourString, Converter={StaticResource LengthConverter}" />

<UserControl.Resources>
    <converter:LengthConverter x:Key="LengthToVisibilityConverter" />
</UserControl.Resources>

那么转换器是:

public class LengthToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string text = (string)value;
        return text.Length > 0 ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

您可以通过直接绑定到文本长度来使其更简洁:

<TextBlock Visibility="{Binding YourString.Length, Converter={StaticResource LengthConverter}" />

在这种情况下,转换器变为:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int length = (int)value;
        return length > 0 ? Visibility.Visible : Visibilty.Collapsed;
    }

在此处了解有关转换器的更多信息:http: //msdn.microsoft.com/en-us/library/system.windows.data.binding.converter (v=vs.110).aspx

于 2013-04-28T22:26:35.967 回答