开发者

WinForms - how to set property value in code and get bound control to update?

I have a WinForms app that contains several comboboxes, numericupdown controls and checkboxes. I also have a data class that exposes several properties and these controls are bound to those properties. Now I need the ability to restore the default values for each of these properties and have all of the bound controls update to reflect the change. For example, one of my comboBox controls is bound to an enum that contains (Red, Blue, Yellow and Green). The default value for this property is set to Blue in my data class constructor. When my app starts up, the combobox that's bound to this property correctly displays Blue as the default selected item. If a user were to select a different color and then decide that they want to revert back to the default color, I need a way to change the property value back to Blue and get the bound control to show that. I can set the property value in code but the problem is that my comboBox doesn't update to reflect the change. I'm guessing there's some kind of change notification mechanism that I need to implement in my data class but I'm not sure what that would be. Any ideas w开发者_开发问答ould be much appreciated. Thanks very much!


You'll need to implement INotifyProperyChanged in your data class like:

public class Coloring : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name != value) {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
    }

    // Do this for all your properties


    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null) {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion
}


If you are using a BindingSource you can call its ResetBindings method.

myBindingSource.ResetBindings(false);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜