سؤال

ولقد وضعت في حاوية ItemsControl (قالب Stackpanel) بلدي UserControls، التي تحصل على إضافتها بشكل حيوي وإزالتها أثناء تشغيل التطبيق. كيف يمكنني الطريق حدث (مثل TextChanged أو GotFocus) الحوض الصغير جميع العناصر في بلدي UserControl (يتكون أساسا من مربعات النص)؟ هذا هو المكان الذي يجب أن تستخدم "المندوبين" أو ICommand؟ أنا جديد على هذا، وربما أنا الخلط بين عدد قليل من الأشياء.

وشكرا!

هل كانت مفيدة؟

المحلول

وأنا أقرأ ما بين السطور لسؤالك لا بأس به، ولكن أظن أنك تريد إرفاقه (وفصل) معالجات الأحداث إلى كل الضوابط أطفالك عند إضافتها (وإزالة).

وحاول وضع ItemsSource الخاص بك إلى ObservableCollection. ثم يمكنك إرفاق معالج حال إلى حال ObservableCollection.CollectionChanged الخاص بك. في معالج الحدث قال يمكنك إرفاق أو فصل معالجات الأحداث لأطفالك عند إضافتها وإزالتها.

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

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top