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

时间:2012-06-19 09:56:55

标签: winforms

在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; }
    }
}

2 个答案:

答案 0 :(得分:2)

我认为您必须尝试处理Mouse和KeyBoard事件:

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));
    }
  }
}

答案 1 :(得分:0)

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