WPF ItemsControl: Route TextChanged evento a todos os itens UserControl
-
06-07-2019 - |
Pergunta
Eu coloquei em um recipiente ItemsControl (modelo StackPanel) meus UserControls, que são adicionados dinamicamente e removido durante a execução do aplicativo. Como posso rota um evento (por exemplo TextChanged ou GotFocus) trough todos os elementos em minha UserControl (consiste principalmente de caixas de texto)? É aqui que eu deveria usar "Delegados" ou ICommand? Eu sou novo para isso e provavelmente estou mixando algumas coisas.
Obrigado!
Solução
Estou lendo nas entrelinhas da sua pergunta um pouco, mas eu suspeito que você deseja anexar (e Separar) manipuladores de eventos para cada um de seus controles filhos como eles são adicionados (e removidos).
Tente configurar sua ItemsSource a uma ObservableCollection. Você pode então anexar um manipulador de eventos para o seu evento ObservableCollection.CollectionChanged. No referido manipulador de eventos você pode anexar ou desanexar manipuladores de eventos para os seus filhos como eles são adicionados e removidos.
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...
}
}