1

在我想知道的 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; }
    }
}
4

2 回答 2

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));
    }
  }
}
于 2012-06-19T12:37:10.340 回答
0

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

于 2012-06-19T11:31:55.317 回答