Search code examples
wpfwpf-controlsexpander

How to make conditional Expander in WPF


I have a very simple task.

I have already created a custom expander so it's working fine.

I just stuck at making it conditional

if my text content is More I want to show expander else I don't want to.

Here is an image of it

I want to achieve this


Solution

  • Sounds like you may need some custom converters. You could do something like this:

    public class LengthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value?.GetType() == typeof(string))
            {
                string text = (string)value;
                return text.Length > 20 ? Visibility.Visible : Visibility.Collapsed;
            }
            return Visibility.Collapsed;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    
    

    Then use it in xaml like this:

    <Window.Resources>
        <local:LengthConverter x:Key="LengthConverter" />
    </Window.Resources>
    
    ...
    
    <Expander Visibility="{Binding SomeText, Converter={StaticResource LengthConverter}}">
        <TextBlock Text="{Binding SomeText}" />
    </Expander>
    
    

    This is not a full solution. I don't know what your expander looks like, and you will want to make it responsive instead of hardcoding the length of the string. But this may put you on the right path.