A read-only CheckBox in C# WPF

后端 未结 11 2074
南方客
南方客 2020-12-06 04:37

I am having a tricky problem, I want some slightly unusual behaviour from a checkbox and can\'t seem to figure it out. Any suggestions would be most welcome. The behaviour I

11条回答
  •  情深已故
    2020-12-06 05:05

    I don't think that creating a whole control for this is necessary. The issue that you're running into comes from the fact that the place where you see 'the check' isn't really the checkbox, it's a bullet. If we look at the ControlTemplate for a CheckBox we can see how that happens (Though I like the Blend template better). As a part of that, even though your binding on the IsChecked property is set to OneWay it is still being updated in the UI, even if it is not setting the binding value.

    As such, a really simple way to fix this, is to just modify the ControlTemplate for the checkbox in question.

    If we use Blend to grab the control template we can see the Bullet inside the ControlTemplate that represents the actual checkbox area.

            
                
                    
                
                
            
    

    In here, the IsChecked and RenderPressed are what are actually making the 'Check' appear, so to fix it, we can remove the binding from the IsChecked property on the ComboBox and use it to replace the TemplateBinding on the IsChecked property of the Bullet.

    Here's a small sample demonstrating the desired effect, do note that to maintain the Vista CheckBox look the PresentationFramework.Aero dll needs to be added to the project.

    
    
        
        
        
        
        
    
    
        
            
                
                    
                
            
    
            
    
            
        
    
    
    

    And the code behind, with our backing Boolean value:

    public partial class Window1 : Window, INotifyPropertyChanged
    {
        public Window1()
        {
            InitializeComponent();
    
            this.DataContext = this;
        }
        private bool myBoolean;
        public bool MyBoolean
        {
            get
            {
                return this.myBoolean;
            }
            set
            {
                this.myBoolean = value;
                this.NotifyPropertyChanged("MyBoolean");
            }
        }
    
        #region INotifyPropertyChanged Members
    
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    
        #endregion
    }
    

提交回复
热议问题