WPF ItemsControl:将TextChanged事件路由到所有UserControl项
-
06-07-2019 - |
题
我已经在ItemsControl容器(Template Stackpanel)中放置了我的UserControls,它在运行应用程序时动态添加和删除。 如何通过UserControl中的所有元素(主要由TextBoxes组成)路由事件(例如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...
}
}
不隶属于 StackOverflow