0

アプリケーションの実行中に動的に追加および削除される UserControls を ItemsControl コンテナー (テンプレート スタックパネル) に配置しました。UserControl (主に TextBox で構成されている) 内のすべての要素を介してイベント (TextChanged や GotFocus など) をルーティングするにはどうすればよいですか? ここで「デリゲート」または ICommand を使用する必要がありますか? 私はこれが初めてで、おそらくいくつかのことを混同しています。

ありがとう!

4

1 に答える 1

1

私はあなたの質問の行間をかなり読んでいますが、コントロールの子が追加(および削除)されるたびに、イベントハンドラーを各コントロールの子にアタッチ(およびデタッチ)したいと考えています。

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

}
于 2009-06-18T19:47:54.913 に答える