For some reason, child Expander
s (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.Handled
to true
in 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 if sender == e.OriginalSource
.
(Woo, 10k...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With