2010-12-07 25 views
2

我有零異常錯誤創建此自定義控件時發送的ValueChanged()事件,並測試它在客戶端:然後在測試形式如何在控件實例化後立即發送自定義事件消息?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Drawing; 
using System.Data; 
using System.Text; 
using System.Windows.Forms; 

namespace customevent 
{ 
    [DefaultEvent("ValueChanged")] 
    public partial class UserControl1 : UserControl 
    { 
     private int m_value; 

     public delegate void ValueChangedHandler(); 
     [Category("Action")] 
     [Description("Value changed.")] 
     public event ValueChangedHandler ValueChanged; 

     public int Value 
     { 
      get { return m_value; } 
      set { 
       m_value = value; 
       ValueChanged(); 
      } 
     } 

     public UserControl1() 
     { 
      InitializeComponent(); 
     } 
     public UserControl1(int iValue) 
     { 
      this.Value = iValue; 
      InitializeComponent(); 
     } 

    } 
} 

自定義控件的來源

private void Form1_Load(object sender, EventArgs e) 
    { 
     userControl11.Value = 100; 
    } 

    private void userControl11_ValueChanged() 
    { 
     MessageBox.Show(userControl11.Value.ToString()); 
    } 

或代替的Form_Load,在構造函數中做到這一點:

private void InitializeComponent() 
    { 
     this.userControl11 = new customevent.UserControl1(100); 

回答

2

你不檢查NULL值:

public int Value 
    { 
     get { return m_value; } 
     set { 
      m_value = value; 
      if(ValueChanged != null) 
      { 
       ValueChanged(); 
      } 
     } 
    } 

此外,你還沒有掛鉤到這個事件在您的形式:

private void Form1_Load(object sender, EventArgs e) 
{ 
    userControl1.ValueChanged += userControl11_ValueChanged; 
    userControl11.Value = 100; 
} 

private void userControl11_ValueChanged() 
{ 
    MessageBox.Show(userControl11.Value.ToString()); 
} 
3

您應該聲明事件處理,因爲這:

public event EventHandler ValueChanged; 

protected virtual void OnValueChanged(object sender, EventArgs e) 
{ 
    if (ValueChanged != null) 
    { 
     ValueChanged(sender, e); 
    } 
} 

public int Value 
{ 
    get { return m_value; } 
    set { 
     if (m_value == value) return; 
     m_value = value; 
     OnValueChanged(this, EventArgs.Empty); 
    } 
} 

PS:有一個接口INotifyPropertyChanged,你應該用它來符合標準的.NET數據綁定規則。

+0

非常感謝INotifyPropertyChanged的建議,不知道怎麼用它了,但似乎很有趣的滿足我的需求。 – user310291 2010-12-07 22:18:35

1

西蒙得你幾乎有:

protected virtual void OnValueChanged(object sender, EventArgs e) 
{ 
    var tmp = ValueChanged; 
    if (tmp != null) 
    { 
     tmp(sender, e); // With the tmp, we won't explode if a subscriber changes the collection of delegates underneath us. 
    } 
} 
+0

對不起,你對我仍然神祕,你是什麼意思的「爆炸」,我看不出有什麼與西蒙的區別:什麼「VAR」增加?謝謝。 – user310291 2010-12-07 22:17:30

相關問題