Search code examples
c#winformsdata-bindingnullable

How to bind TextBox to a nullable property only if a CheckBox is checked


I need to bind TextBox.Text to a property if the CheckBox next to it is checked. Otherwise the value of property should be null.

TextBox binding to nullable

Let's say DTO Class is like:

public class DataForInputDTO 
{
    public double? Power {get; set;}
    public double? Speed {get; set;} 
    // Other Properties
}

Now, when user unchecks the Speed CheckBox the TextBox next to it gets disabled (This is OK) but I also need the property Speed to get null instead of 60. Is there any way to do this without manually changing the binding at CheckBox.CheckedChaneg?


Solution

  • You can set via the property to which the Speed CheckBox is bound to. For example, if the IsChecked Property of Speed checkbox is bound to a property called IsSpeedChecked, you could do the following.

        private double _powerValue = 0;
    
        public double? Power { get; set; } = 0;
    
        public bool IsPowerEnabled
        {
            get => _isPowerEnabled;
            set
            {
                _isPowerEnabled = value;
                if (!value)
                {
                    _powerValue = Power.Value;
                    Power = null;
                }
                else
                {
                    Power = _powerValue;
                }
                NotifyOfPropertyChange(nameof(Power));
                NotifyOfPropertyChange(nameof(IsPowerEnabled));
            }
        }