Silverlight Bind to inverse of boolean property value

后端 未结 3 1141
清酒与你
清酒与你 2021-02-08 05:43

I want to bind a controls visibility to inverse of boolean property value. I have a property CanDownload, if it is true then I want to hide textbox and vice versa. How can I ach

3条回答
  •  眼角桃花
    2021-02-08 06:15

    I use a BoolToVisibilityConverter that allows you to pass "Inverse" as the ConverterParameter to inverse the conversion and show only if the property is false.

    public class BoolToVisibilityConverter : IValueConverter
    {
        /// TargetType must be Visibility
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(!(value is bool))
                throw new ArgumentException("Source must be of type bool");
    
            if(targetType != typeof(Visibility))
                throw new ArgumentException("TargetType must be Visibility");
    
            bool v = (bool) value;
    
            if(parameter is string && parameter.ToString() == "Inverse")
                v = !v;
    
            if (v)
                return Visibility.Visible;
            else
                return Visibility.Collapsed;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

提交回复
热议问题