2013-04-28 59 views
0

如何使textBlock自動隱藏,如果在Windows Phone 7應用程序中爲空(C#,silverlight,xaml)?在windows phone 7中隱藏空textBlock?

我知道WPF有一個類似的問題,但它似乎不適用於silverlight。

+0

您在使用上的TextBlock或不綁定? – Kenneth 2013-04-28 22:23:47

回答

8

您可以使用轉換器:

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

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

然後轉換爲:

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

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(); 
    } 
} 

你可以通過綁定直接文本長度使這稍微乾淨在這種情況下,轉換器變成:

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