2017-07-26 68 views
-2

我想這樣的,但它會返回空值,:如何在沒有委託的情況下在c#中創建事件?

public event EventHandler<EventArgs> myevent; 


public void Btn_Click(object sender, EventArgs e) 
{ 

    if (myevent!= null) //Here I get null value. 
     myevent(null, new EventArgs()); 
} 

如何實現的情況下火?

編輯:

我具有其中包含按鈕事件,該方法ButtonClick我建立這個事件內該用戶控制一個UserControl

我有一個Form。在這種形式中我使用這個UserControl。所以我需要從用戶控件按鈕單擊事件觸發一個事件來形成頁面特定的功能。

+3

因爲沒有人在您的活動中註冊 – Rahul

+2

您尚未向您的活動註冊任何處理程序方法,因此在您提出活動時您希望運行什麼? https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-subscribe-to-and-unsubscribe-from-events –

+0

以下鏈接對您有幫助問題: [有或沒有代表的事件](https://stackoverflow.com/questions/1334736/events-with-and-without-delegates-in-asp-net) – Viswa

回答

0

我爲你寫了一個非常簡單的基本解決方案。請閱讀代碼中的註釋以瞭解解決方案。如果有什麼不清楚的地方,請提問。

下面的示例,將導致事件,火災,如果人的名稱更改:

這裏是Person對象:

public class Person 
{ 
    //Event to register to, when you want to capture name changed of person 
    public event EventHandler<NameChangedEventArgs> nameChangedEvent; 

    //Property 
    private string _name; 
    public string Name 
    { 
     get { return _name; } 
     set 
     { 
      this._name = value; 
      //Call the event. This will trigger the OnNameChangedEvent_Handler 
      OnNameChangedEvent_Handler(new NameChangedEventArgs() {NewName = value}); 
     } 
    } 

    private void OnNameChangedEvent_Handler(NameChangedEventArgs args) 
    { 
     //Check if event is null, if not, invoke it. 
     nameChangedEvent?.Invoke(this, args); 
    } 
} 

//Custom event arguments class. This is the argument type passed to your handler, that will contain the new values/changed values 
public class NameChangedEventArgs : EventArgs 
{ 
    public string NewName { get; set; } 
} 

下面是一個實例,並使用Person對象的代碼:

class Program 
{ 

    static void Main(string[] args) 
    { 
     //Instantiate person object 
     var person = new Person(); 
     //Give it a default name 
     person.Name = "Andrew"; 

     //Register to the nameChangedEvent, and tell it what to do if the person's name changes 
     person.nameChangedEvent += (sender, nameChangedArgs) => 
     { 
      Console.WriteLine(nameChangedArgs.NewName); 
     }; 

     //This will trigger the nameChanged event. 
     person.Name = "NewAndrewName"; 

     Console.ReadKey(); 


    } 
} 
+0

謝謝,我試過了,但是事件沒有開火 – user8331467

+0

用上面的代碼?事件確實發生了... –

+0

我試過這個概念給我的代碼,但是事件沒有發生火災 – user8331467

0

能不能請你調用事件的以下方式:

public event EventHandler myevent; 
myevent += new EventHandler(Button1_Click); 

     if (myevent != null) //Here I get null value. 
      myevent(1, new EventArgs()); 
相關問題