For some reason, child Expanders (placed in a StackPanel inside of another Expander), when collapsed or expanded, cause the parent Expander to raise its Expanded or Collapsed events.
Anyone know why this is or how I can change it? I’m only interested in the parent’s events.
Here is some test XAML:
<Expander Header="Outer" Expanded="Expander_Expanded" Collapsed="Expander_Collapsed">
<StackPanel>
<Expander Header="Inner1">
<Canvas Height="100" Width="100" Background="Blue" />
</Expander>
<Expander Header="Inner2">
<Canvas Height="100" Width="100" Background="Red" />
</Expander>
</StackPanel>
</Expander>
and here is the code-behind:
private void Expander_Expanded(object sender, RoutedEventArgs e)
{
MessageBox.Show("expanded");
}
private void Expander_Collapsed(object sender, RoutedEventArgs e)
{
MessageBox.Show("collapsed");
}
When you run this, if you expand the parent, you get an “expanded” messagebox, as you’d expect. But when you then expand one of the children, you get the messagebox again.
The documentation for the Expanded event says:
The Expanded event occurs when the IsExpanded property changes from false to true
But clearly the IsExpanded property isn’t changing on the parent Expander.
Why is this happening, any ideas?
Those events are routed and bubble up in the tree, if you want to prevent the parents from handling the event and thus reacting to it, set
e.Handledtotruein the child expander’s event handler.Edit: Instead of preventing the event from being raised you also could just restrict the code-execution in the handler to the case when the actual expander where the handler is attached raised the event. You can do this by wrapping everything in an
if-block which executes ifsender == e.OriginalSource.(Woo, 10k…)