WPF ItemsControl:すべてのUserControlアイテムにTextChangedイベントをルーティングします

StackOverflow https://stackoverflow.com/questions/1011839

質問

UserControlsをItemsControlコンテナ(テンプレートStackpanel)に配置しました。これは、アプリケーションの実行中に動的に追加および削除されます。 UserControlのすべての要素(主にTextBoxで構成されている)を介してイベント(TextChangedやGotFocusなど)をルーティングするにはどうすればよいですか? これは、「デリゲート」を使用すべき場所ですか?または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