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 に答える