简体   繁体   中英

Setting value of a bound property from the setter of another bound property

I have a business object in C# which implements INotifyPropertyChanged and contains several bound properties. In a nutshell, it looks like this:

public class BusinessObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, e);
        }
    }

    private int _intProperty;
    public int IntProperty // bound to NumericUpDown control
    {
        get { return _intProperty; }
        set
        {
            if (_intProperty == value)
            {
                return;
            }

            _intProperty = value;
            OnPropertyChanged(new PropertyChangedEventArgs("IntProperty"));

            // if IntProperty is > 10, then set BoolProperty to false
            if (value > 10)
            {
                this.BoolProperty = false;
                //OnPropertyChanged(new PropertyChangedEventArgs("BoolProperty"));
            }
        }
    }

    private bool _boolProperty;
    public bool BoolProperty // bound to CheckBox
    {
        get { return _boolProperty; }
        set
        {
            if (_boolProperty == value)
            {
                return;
            }

            _boolProperty = value;
            OnPropertyChanged(new PropertyChangedEventArgs("BoolProperty"));
        }
    }

As you can see in the setter for IntProperty, I'm setting the BoolProperty = false when IntProperty has been set > 10. BoolProperty is bound to a CheckBox in my UI (winforms) but even though I'm setting BoolProperty = false, the CheckBox doesn't update to reflect that change until the control that's bound to IntProperty loses focus. I thought maybe I needed to call OnPropertyChanged after I set BoolProperty = false but that didn't seem to make a difference. Is this the expected behavior in this scenario? If so, is it possible to implement the behavior that I've described?

您可能需要将绑定的DataSourceUpdateMode设置为DataSourceUpdateMode.OnPropertyChanged

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM