【问题标题】:WPF ItemsControl: Route TextChanged Event to all UserControl ItemsWPF ItemsControl:将 TextChanged 事件路由到所有 UserControl 项
【发布时间】:2009-06-18 09:49:33
【问题描述】:

我已将我的 UserControls 放入 ItemsControl Container (Template Stackpanel) 中,这些控件在运行应用程序时会被动态添加和删除。 如何通过我的 UserControl(主要由 TextBoxes 组成)中的所有元素路由事件(例如 TextChanged 或 GotFocus)? 这是我应该使用“代表”还是 ICommand 的地方?我是新手,可能我混淆了一些东西。

谢谢!

【问题讨论】:

    标签: c# wpf user-controls command routed


    【解决方案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...
           }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多