2009-06-18 109 views
0

我已經放置在一個ItemsControl容器(模板Stackpanel)中,我的UserControls在運行應用程序時被動態添加和刪除。 如何路由一個事件(例如TextChanged或GotFocus)通過我的UserControl中的所有元素(主要由文本框組成)? 這是我應該使用「Delegates」還是ICommand?我對此很陌生,可能我正在混合一些東西。WPF ItemsControl:將TextChanged事件路由到所有UserControl項目

謝謝!

回答

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

}