【问题标题】:How to know an event handled by User or Application Methods?如何知道用户或应用程序方法处理的事件?
【发布时间】:2015-08-02 23:52:38
【问题描述】:

我有一个Control,比如DataGridView,并为此声明了几个事件。

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

现在,当我想在网格中插入几条记录时,还有SelectionChanged,因为它们每一条都被执行,而我不想调用SelectionChanged事件! 这只是我在事件中遇到的问题的一个例子。

总之,我的问题是,如何知道这个事件处理的原因是用户还是应用程序方法被执行了? 换句话说,如何知道这个SelectionChanged 事件是由用户运行的还是由一个称为那个的方法运行的?

【问题讨论】:

  • 使用布尔标志指示事件是从方法调用中触发的
  • @SriramSakthivel 这不是个好主意,用标志字段填写所有项目!
  • 没有其他通用方法可以解决您的问题。如果你找到了请告诉我。谢谢。
  • @SriramSakthivel 我需要一个处理程序和侦听器方法之间的接口方法。例如:myControl.SelectionChanged += (s, e) => JustCallByUser(myControl_SelectionChanged(s, e))。非常感谢您的回答。

标签: c# winforms events controls


【解决方案1】:

我不知道,但我通过创建一种方法解决了此类问题,该方法在控件中生成了我想要的内容(编辑单元格,离开单元格,离开一行,添加一行,更改选择...在您的例如)忽略事件处理程序。

例如,如果我有一个 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;
    }

【讨论】:

  • 删除处理程序是个坏主意,因为存在很多事件!如果发生一个异常,那么所有事件都会丢失!
  • 我需要一个方法来从中调用事件,它决定是否运行!
  • 我想我不太明白你最后的评论。你能说得更清楚些吗?
  • 我需要一个处理程序和侦听器方法之间的接口方法。例如:myControl.SelectionChanged += (s, e) =&gt; JustCallByUser(myControl_SelectionChanged(s, e))
【解决方案2】:

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

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

请表达你的cmets!谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2023-03-14
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多