0
votes

I've placed in a ItemsControl Container (Template Stackpanel) my UserControls, which get dynamically added and removed while running the application. How can I route an Event (e.g. TextChanged or GotFocus) trough all elements in my UserControl (consists mainly of TextBoxes)? Is this where I should use "Delegates" or ICommand? I'm new to this and probably I'm mixing up a few things.

Thanks!

1

1 Answers

1
votes

I'm reading between the lines of your question quite a bit, but I suspect you want to attach (and detach) event handlers to each of your controls children as they are added (and removed).

Try setting your ItemsSource to an ObservableCollection. You can then attach an event handler to your ObservableCollection.CollectionChanged event. In said event handler you can attach or detach event handlers to your children as they are added and removed.

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

}