How can you get a XAML TextBlock to collapse when it contains no data?

后端 未结 3 547
臣服心动
臣服心动 2020-12-29 08:19

I want to tell WPF: \"If TextBlock contains no data, then don\'t show it.\"

TRY #1 with a simple trigger produces

相关标签:
3条回答
  • 2020-12-29 08:56

    The easiest, simplest and quickest way are converters. So, why not KISS? (keep it simple, stupid)?

    To implement converter classes only a few lines of code are necessary.

    Converter:

    public class StringToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return string.IsNullOrWhiteSpace((string)value) ? Visibility.Collapsed : Visibility.Visible;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var visiblity = (Visibility)value;
            return visiblity == Visibility.Visible;
        }
    }
    

    Usage:

    Include namespace: xmlns:c="clr-namespace:Hfr.Windows.Controls"

    Define resource: <c:StringToVisibilityConverter x:Key="StringToVisiblity"/>

    Use it:

    <TextBlock
        Text="{Binding SomeStringPropertyValue}"
        TextWrapping="Wrap"
        Visibility="{Binding SomeStringPropertyValue, Converter={StaticResource StringToVisiblity}}" />
    

    Since you'll use your converters in multiple projects, implement the converter classes in a "common library".

    0 讨论(0)
  • 2020-12-29 09:00

    I think the simplest way to do this would be to define a Converter which converts string to visibility.

       ...
    
       return string.IsNullOrEmpty(s) ? Visibility.Collapsed : Visibility.Visible;
    }
    

    Then just

    <TextBlock Visibility="{StaticResource StringToVisibilityConverter}"
    
    0 讨论(0)
  • 2020-12-29 09:03

    Either Try #2 or Try #3 should be fine - the problem is in the line where you are referencing the style - you need to use either 'Style="{StaticResource [KeyName]}"' or 'Style="{DynamicResource [KeyName]}"'.

    Try this (in Try #2):

    <StackPanel Margin="10">        
        <TextBlock Style="{StaticResource MainMessageStyle}" Padding="10" Background="Yellow" Text="{Binding MainMessage}"/>
    </StackPanel>
    

    In Try 1 you reveal a limitation of current WPF versions: Triggers are not supported directly on elements.

    0 讨论(0)
提交回复
热议问题