Winforms 如何在复选框中查找检查状态更改的来源

Winforms 如何在复选框中查找检查状态更改的来源,winforms,Winforms,在CheckedChanged事件中,我想知道是哪个操作触发了此更改,或者是用户显式单击了复选框,或者是从数据绑定更新的 public partial class Form1 : Form { public Form1() { InitializeComponent(); Source = new ValueSource(); this.checkBox1.DataBindings.Add(new Binding("Checked"

在CheckedChanged事件中,我想知道是哪个操作触发了此更改,或者是用户显式单击了复选框,或者是从数据绑定更新的

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Source = new ValueSource();
        this.checkBox1.DataBindings.Add(new Binding("Checked", Source, "State", false, DataSourceUpdateMode.OnPropertyChanged));
        this.checkBox1.CheckedChanged += new EventHandler(checkBox1_CheckedChanged);
    }

    void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        // databinding changed the value.
        MessageBox.Show("Value changed from data binding");
        // user checked the check box using mouse.
        MessageBox.Show("Value changed due to use action");
    }

    public ValueSource Source { get; set; }
}

public class ValueSource
{
    private bool state = true;

    public bool State 
    {
        get { return state; }
        set { state = value; }
    }
}

我认为最好的方法是分别处理“CollectionChanged”和“click”事件。

我认为您必须尝试处理鼠标和键盘事件:

public ValueSource Source { get; set; }
private bool _FromUser = false;

public Form1() {
  InitializeComponent();

  Source = new ValueSource();
  this.checkBox1.DataBindings.Add(new Binding("Checked", Source, "State", false, DataSourceUpdateMode.OnPropertyChanged));
  this.checkBox1.CheckedChanged += new EventHandler(checkBox1_CheckedChanged);

  this.checkBox1.MouseDown += new MouseEventHandler(checkBox1_MouseDown);
  this.checkBox1.MouseUp += new MouseEventHandler(checkBox1_MouseUp);
  this.checkBox1.KeyDown += new KeyEventHandler(checkBox1_KeyDown);
  this.checkBox1.KeyUp += new KeyEventHandler(checkBox1_KeyUp);
}

void checkBox1_KeyDown(object sender, KeyEventArgs e) {
  _FromUser = true;
}

void checkBox1_KeyUp(object sender, KeyEventArgs e) {
  _FromUser = false;
}

void checkBox1_MouseDown(object sender, MouseEventArgs e) {
  _FromUser = true;
}

void checkBox1_MouseUp(object sender, MouseEventArgs e) {
  _FromUser = false;
}

void checkBox1_CheckedChanged(object sender, EventArgs e) {
  MessageBox.Show("From User = " + _FromUser.ToString());
}
此外,ValueSource类应实现
INotifyPropertyChanged
事件:

public class ValueSource : INotifyPropertyChanged {
  public event PropertyChangedEventHandler PropertyChanged;

  private bool state = true;

  public bool State {
    get { return state; }
    set {
      state = value;
      OnPropertyChanged("State");
    }
  }

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

此问题在延迟状态下关闭。您可能想钩住复选框的
鼠标
相关事件并加以区分?