2009-06-18 149 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... 
     } 

}