简体   繁体   中英

How to programmatically specify one-way binding in C#?

Simple C# question, but I have been unable to find the answer, despite much searching. (I think I know how it works in WPF XAML file, but I am using WinForms and binding programmatically). This must be simple. How do I tell it to bind one-way?

In this case, chkUnchkAllChkBx is a check box. AllCheckBoxesChecked is boolean = true if all checkboxes in a certain panel are checked. (Content of panel is not known in advance).

-Aram

        public AllCheckBoxesChecked panelCheckBoxesChecked = new AllCheckBoxesChecked();        
    chkUnchkAllChkBx.DataBindings.Add("Checked",panelCheckBoxesChecked,"AllChecked");
    
    public class AllCheckBoxesChecked : INotifyPropertyChanged
    { private bool _allChecked;

        public AllCheckBoxesChecked()
        {
            _allChecked = false;
        }
        public bool AllChecked
        {
            get { return _allChecked; }
            set
            {
                _allChecked = value;
                OnPropertyChanged("AllChecked");
            }
        }
       public event PropertyChangedEventHandler PropertyChanged;

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

There is no equivalent in WinForms of WPF's BindingMode. So let's clarify the issue. There should only be a problem if, when value of AllCheckBoxesChecked.AllChecked is changed by changing the value of the bound CheckBox chkUnchkAllChkBx, there is an unwelcome effect in the application, such as if the values of all the CheckBoxes in the 'certain' panel were to be changed to the same value as chkUnchkAllChkBx.

Assuming you do have a problem along those lines, you just need to make sure that the way the binding class AllCheckBoxesChecked is used does not cause problems. A simple way that might work, depending on your application, would be to make AllCheckBoxesChecked.AllChecked a get-only property, with the value of its backing field set by a method. Something like this:

public bool AllChecked
    {
        get { return _allChecked; }
    }

public void SetAllChecked(bool value)
    {
        _allChecked = value;
        OnPropertyChanged("AllChecked");
    }

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