Bind visibility property to a variable

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

I have a Border with Label inside a Window,



        
5条回答
  •  庸人自扰
    2020-12-05 14:26

    You can't bind field. You can only bind public properties or dependency properties.

    Using public property (you have to implement INotifyPropertyChanged interface to have property->binding):

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private bool vis;
        public bool Vis
        {
            get { return vis; }
            set
            {
                if (vis != value)
                {
                    vis = value;
                    OnPropertyChanged("Vis");  // To notify when the property is changed
                }
            }
        }
    
        public MainWindow()
        {
            InitializeComponent();
    
            Vis = true;
            // DataContext explains WPF in which object WPF has to check the binding path. Here Vis is in "this" then:
            DataContext = this;          
        }
    
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Vis = !Vis;  // Test Code
        }
    
        #region INotifyPropertyChanged implementation
        // Basically, the UI thread subscribes to this event and update the binding if the received Property Name correspond to the Binding Path element
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }
    

    The XAML code is:

    
    
        
            
            
        
    
        
            

提交回复
热议问题