2012-01-29 30 views
1

我正在尋找一個優雅的方式來跟蹤值組合框之間的變化。我期望做的是在SelectionChanged事件發生時觸發自定義事件,但僅限於特定的值更改。這意味着要知道初始值是什麼。只有當初始值從z改變時,該事件纔會被觸發。如果初始值爲a,b或c,則該事件不會被觸發。但如果初始值是z,它將被觸發。最簡單的方法來監視組合框值之間的變化

有沒有人有一個優雅的方式來解決這個問題?

+0

哪種編程語言? – emaillenin 2012-01-29 04:59:50

+0

沒錯。對此感到悲傷。我正在使用.NET環境。 C#和VS2010更具體。 – user953710 2012-01-29 23:17:36

回答

1

爲此,您需要創建一個自定義事件處理程序,並且可以自定義事件參數,

//Event Handler Class 
public class SpecialIndexMonitor 
{ 
     public event EventHandler<SpecialIndexEventArgs> SpecialIndexSelected; 
     //Custom Function to handle Special Index 
     public void ProcessRequest(object sender, System.EventArgs e) 
     { 
      //Your custom logic 
      //Your code goes here 
      //Raise event 
      if(SpecialIndexSelected != null) 
      { 
       SpecialIndexEventArgs args = new SpecialIndexEventArgs{ 
        SelectedIndex = ((ComboBox) sender).SelectedIndex; 
       }; 
       SpecialIndexSelected(this, args); 
      } 
     } 
} 

//Custom Event Args 
public class SpecialIndexEventArgs : EventArgs 
{ 
    //Custom Properties 
    public int SelectedIndex { get; set; } //For Example 
    //Default Constructor 
    public SpecialIndexEventArgs() 
    { 
    } 
} 

內,您的形式

//Hold previous value 
private string _previousItem; 

//IMPORTANT: 
//After binding items to combo box you will need to assign, 
//default selected item to '_previousItem', 
//which will make sure SelectedIndexChanged works all the time 

// Usage of Custom Event 
private void comboBox1_SelectedIndexChanged(object sender, 
    System.EventArgs e) 
{ 
     string selectedItem = (string)comboBox1.SelectedItem; 
     if(string.Equals(_previousItem,) 
     switch(_previousItem) 
     { 
      case "z": 
      { 
       SpecialIndexMonitor spIndMonitor = new SpecialIndexMonitor(); 
       spIndMonitor.SpecialIndexSelected += 
        new EventHandler<SpecialIndexEventArgs>(SpecialIndexSelected); 
       break; 
      } 
      case "a": 
      case "b": 
       break; 
     } 
     _previousItem = selectedItem; //Re-Assign the current item 
} 
void SpecialIndexSelected(object sender, SpecialIndexEventArgs args) 
{ 
    // Your code goes here to handle the special index 
} 

有沒有編譯的代碼,但在邏輯上它應該爲你工作。

相關問題