Domanda

Ho inserito in un Container ItemsControl (Template Stackpanel) i miei UserControls, che vengono aggiunti e rimossi in modo dinamico durante l'esecuzione dell'applicazione. Come posso instradare un evento (ad esempio TextChanged o GotFocus) attraverso tutti gli elementi nel mio UserControl (costituito principalmente da TextBox)? È qui che dovrei usare " Delegati " o ICommand? Sono nuovo di questo e probabilmente sto mescolando alcune cose.

Grazie!

È stato utile?

Soluzione

Sto leggendo un po 'tra le righe della tua domanda, ma sospetto che tu voglia collegare (e scollegare) i gestori di eventi a ciascuno dei tuoi bambini di controllo mentre vengono aggiunti (e rimossi).

Prova a impostare la tua ItemsSource su ObservableCollection. È quindi possibile collegare un gestore eventi all'evento ObservableCollection.CollectionChanged. Nel suddetto gestore eventi puoi collegare o scollegare i gestori eventi ai tuoi figli mentre vengono aggiunti e rimossi.

public class MyContainer : StackPanel
{
   public MyContainer()
   {
      this.ItemsSource = MyCollection;
   }

   ObservableCollection<UIElement> myCollection;
   public ObservableCollection<UIElement> MyCollection
   {
      get
      {
         if (myCollection == null)
         {
             myCollection = new ObservableCollection<UIElement>();
             myCollection.CollectionChanged += new NotifyCollectionChangedEventHandler(myCollection_CollectionChanged);
         }
         return myCollection;
   }

   void myCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
   {
       foreach (UIElement removed in e.OldItems)
       {
          if (added is TextBox)
             (added as TextBox).TextChanged -= new Removeyoureventhandler here...

          if (added is someotherclass)
             (added as someotherclass).someotherevent += Removesomeothereventhandler here...              
       }

       foreach (UIElement added in e.NewItems)
       {
          if (added is TextBox)
             (added as TextBox).TextChanged += new Addyoureventhandler here...

          if (added is someotherclass)
             (added as someotherclass).someotherevent += Addsomeothereventhandler here...
       }

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top