在Windows Phone 7中隐藏空文本块?

时间:2013-04-28 22:17:37

标签: c# windows-phone-7 xaml

如果在Windows Phone 7应用程序(C#,silverlight,xaml)中为空,如何使textBlock自动隐藏?

我知道WPF有一个类似的问题,但它似乎不适用于silverlight。

1 个答案:

答案 0 :(得分: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