1

我正在寻找一种优雅的方式来跟踪组合框的值之间的变化。我要做的是在 SelectionChanged 事件发生时触发自定义事件,但仅针对特定值更改。这意味着知道初始值是什么。仅当初始值从 z 更改时才会触发该事件。如果初始值为 a、b 或 c,则不会触发该事件。但如果初始值为 z,它将被触发。

有没有人有优雅的方法来解决这个问题?

4

1 回答 1

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
 }

尚未编译代码,但从逻辑上讲它应该适合您。

于 2012-01-30T05:07:57.647 回答