Pregunta

He colocado en un Contenedor de control de elementos (Panel de pila de plantillas) mis controles de usuario, que se agregan y eliminan dinámicamente mientras se ejecuta la aplicación. ¿Cómo puedo enrutar un Evento (por ejemplo, TextChanged o GotFocus) a través de todos los elementos en mi UserControl (consiste principalmente en TextBoxes)? ¿Es aquí donde debo usar " Delegados " o ICommand? Soy nuevo en esto y probablemente estoy mezclando algunas cosas.

¡Gracias!

¿Fue útil?

Solución

Estoy leyendo bastante entre líneas de su pregunta, pero sospecho que desea adjuntar (y desconectar) los controladores de eventos a cada uno de sus elementos secundarios de control a medida que se agregan (y eliminan).

Intente configurar su ItemsSource en una ObservableCollection. Luego puede adjuntar un controlador de eventos a su evento ObservableCollection.CollectionChanged. En dicho controlador de eventos, puede adjuntar o separar los controladores de eventos a sus hijos a medida que se agregan y eliminan.

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...
       }

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top