Bind visibility property to a variable

前端 未结 5 725
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 14:12

I have a Border with Label inside a Window,



        
5条回答
  •  一向
    一向 (楼主)
    2020-12-05 14:22

    First you will need to make vis a Property:

    private bool _vis;
    
    public bool Vis
    {
        get{return _vis;}
        set
        {
            if(_vis != value)
            {
                _vis = value;
            }
        }
    }
    

    Then you will need a ValueConverter.

    [ValueConversion(typeof(bool), typeof(Visibility))]
        public class VisibilityConverter : IValueConverter
        {
            public const string Invert = "Invert";
    
            #region IValueConverter Members
    
            public object Convert(object value, Type targetType, object parameter,
                System.Globalization.CultureInfo culture)
            {
                if (targetType != typeof(Visibility))
                    throw new InvalidOperationException("The target must be a Visibility.");
    
                bool? bValue = (bool?)value;
    
                if (parameter != null && parameter as string == Invert)
                    bValue = !bValue;
    
                return bValue.HasValue && bValue.Value ? Visibility.Visible : Visibility.Collapsed;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter,
                System.Globalization.CultureInfo culture)
            {
                throw new NotSupportedException();
            }
            #endregion
        }
    

    You will need to create an instance of the converter like so in your resources:

    
        
    
    

    Then you can bind your border like so:

    
        
    
    

提交回复
热议问题