How to Implement a BoolToVisibilityConverter

前端 未结 3 984
小蘑菇
小蘑菇 2020-12-06 10:11

In my app I would like to toggle the visibility of an item in a StackPanel. My Stackpanel contains an Image and a TextBlock. How would I properly use a BoolToVisibilityConve

相关标签:
3条回答
  • 2020-12-06 10:45

    Here is mine:

    public class BoolToVisConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return value is Visibility && (Visibility)value == Visibility.Visible; 
        }
    }
    
    0 讨论(0)
  • 2020-12-06 10:50

    There is already an implemenation of the converter: http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter(v=vs.110).aspx

    0 讨论(0)
  • 2020-12-06 11:00

    Try this:

    public class BooleanToVisibilityConverter : IValueConverter
    {
        private object GetVisibility(object value)
        {
            if (!(value is bool))
                return Visibility.Collapsed;
            bool objValue = (bool)value;
            if (objValue)
            {
                return Visibility.Visible;
            }
            return Visibility.Collapsed;
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return GetVisibility(value);
        }
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    
    
    }
    
    0 讨论(0)
提交回复
热议问题