Boolean to Visibility Converter - inverted?

前端 未结 2 1378
礼貌的吻别
礼貌的吻别 2020-12-22 02:27

how do i do something like this




     

        
相关标签:
2条回答
  • 2020-12-22 03:04

    From @K Mehta (https://stackoverflow.com/a/21951103/1963978), with slight updates for the method signature for Windows 10 Universal applications (Changing from "CultureInfo culture" to "string language", per https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh701934.aspx) :

    public class BooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType,
            object parameter, string language)
        {
            bool boolValue = (bool)value;
            boolValue = (parameter != null) ? !boolValue : boolValue;
            return boolValue ? Visibility.Visible : Visibility.Collapsed;
        }
    
        public object ConvertBack(object value, Type targetType,
            object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
    
    0 讨论(0)
  • 2020-12-22 03:12

    As far as I know, you have to write your own implementation for this. Here's what I use:

    public class BooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool boolValue = (bool)value;
            boolValue = (parameter != null) ? !boolValue : boolValue;
            return boolValue ? Visibility.Visible : Visibility.Collapsed;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    And I generally set ConverterParameter='negate' so it's clear in code what the parameter is doing. Not specifying a ConverterParameter makes the converter behave like the built-in BooleanToVisibilityConverter. If you want your usage to work, you can, of course, parse the ConverterParameter using bool.TryParse() and react to it.

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