Silverlight Bind to inverse of boolean property value

后端 未结 3 1083
清酒与你
清酒与你 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:21

    I was able to solve this for a recent project using a bool to visibility converter:

    public class BoolToVisibilityConverter : IValueConverter
    {
    
        #region IValueConverter Members
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value.GetType().Equals(typeof(bool)))
            {
                if ((bool)value == true)
                    return Visibility.Visible;
                else
                    return Visibility.Collapsed;
            }
            else
                return Visibility.Visible;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value.GetType().Equals(typeof(Visibility)))
            {
                if ((Visibility)value == Visibility.Collapsed)
                    return false;
                else
                    return true;
            }
            else
                return false;
    
        }
    
        #endregion
    }    
    

    I think I could have probably replaced this line:

    if (value.GetType().Equals(typeof(Visibility)))
    

    with something more simple like this:

    if (value is Visibility)
    

    same with the bool GetType, but you get the idea.

    Of course, in your converter you can reverse the visility values based on your visibility needs. Hope this helps a little.

提交回复
热议问题