如何知道用户或应用程序方法处理的事件?

How to know an event handled by User or Application Methods?

我有一个 Control like a DataGridView 和为此声明的几个事件。

例如: CellEndEdit, CellLeave, RowLeave, RowsAdded, SelectionChanged, ...

现在,当我要向网格中插入多条记录时,还有SelectionChanged for every one of them is executed, while I did not want to call SelectionChanged 事件! 这只是我在活动中遇到的问题的一个例子。

综上所述,我的问题是,如何知道这个事件处理的原因是用户还是应用程序方法被执行了? 换句话说,如何知道此 SelectionChanged 事件由用户或调用该事件的方法运行?

我不知道,但我通过创建一个方法解决了这个问题,该方法使控件成为我想要的(编辑单元格、保留单元格、保留一行、添加一行、更改选择...在你的例子中)忽略事件处理程序。

例如,如果我有一个 TextBox 并且我想在不监听事件文本更改的情况下更新它,我会这样做:

    textBox.TextChanged -= eventHandler;
    textBox.Text = text;
    textBox.TextChanged += eventHandler;

你可以用这样的方法封装它:

    /// <summary>
    /// Assigns text to textBox.Text ignoring the event handler eventHandler for the event TextChanged.
    /// </summary>
    /// <param name="textBox">Text box control.</param>
    /// <param name="eventHandler">Event handler to ignore.</param>
    /// <param name="text">Text to assign.</param>
    public static void AssignSilently(TextBox textBox, EventHandler eventHandler, string text)
    {
        textBox.TextChanged -= eventHandler;
        textBox.Text = text;
        textBox.TextChanged += eventHandler;
    }

我认为这个答案是正确的:

public void JustCallEventByUser<TEventArgs>(Action<object, TEventArgs> method, object sender, TEventArgs e) where TEventArgs : EventArgs
{
    var frames = new System.Diagnostics.StackTrace().GetFrames();

    if (frames == null) return;

    //
    // This method (frames[0]= 'JustCallEventByUser') and declaration listener method (frames[1]= '(s, e)=>') must be removed from stack frames
    if (!frames.Skip(2).Any(x =>
    {
        Type declaringType = x.GetMethod().DeclaringType;
        return declaringType != null && declaringType.Name == this.Name;
    }))
    {  method.Invoke(sender, e); }
}

我创建了一个在侦听器和事件之间播放接口字符的方法。在那我检查 StackTrace 知道谁叫我 运行 听众 !

用法示例:

gridViewMain.SelectionChanged += (s, e) =>
         JustCallEventByUser(gridViewMain_SelectionChanged, s, e);

请发表您的意见!谢谢