簡體   English   中英

C#使用自定義eventargs覆蓋事件

[英]C# override event with custom eventargs

我需要一個自定義的NumericUpDown,其中事件ValueChanged應該傳遞CancelEventArgs而不是EventArgs,因為我希望能夠在驗證某些條件時取消編輯(例如,我有兩個NumericUpDown必須始終具有不同的值)。 如果我嘗試覆蓋OnValueChanged,顯然會得到一個錯誤。

protected override void OnValueChanged(CancelEventArgs e)
{
    if (e.Cancel)
        return;
    else
    {
        EventArgs args = (EventArgs)e;
        base.OnValueChanged(args);
    }
}

有沒有辦法做到這一點?

我建議稍微更改一下cancel行為的實現,而不是嘗試通過事件參數傳遞Cancellation的信息,而是可以通過在自定義組件中引入新事件來按需查詢它。 這是一個簡單的示例:

  class CustomNumericUpDown : NumericUpDown
  {
    protected override void OnValueChanged(EventArgs e)
    {
        if (QueryCancelValueChanging != null && QueryCancelValueChanging())
            return;
        else
        {
            EventArgs args = (EventArgs)e;
            base.OnValueChanged(args);
        }
    }

    public event Func<bool> QueryCancelValueChanging;
}

在這種情況下,組件的主機可以訂閱新事件,以決定是否取消“ ValueChanged”事件。

編輯:用法示例:

 public partial class Form1 : Form
 {
    public Form1()
    {
        InitializeComponent();

        CustomNumericUpDown nudTest = new CustomNumericUpDown();
        nudTest.QueryCancelValueChanging += NudTest_QueryCancelValueChanging;
    }

    private bool NudTest_QueryCancelValueChanging()
    {
        return true;/* Replace by custom condition here*/
    }
}

如果您以前從未做過,也許您需要學習如何創建和管理自定義事件,因此在網絡上可以輕松找到有關此主題的教程( 如本教程)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM