子扩展器引发父扩展器的展开和折叠事件?
由于某种原因,子 Expander
(放置在另一个 Expander
内的 StackPanel
中)在折叠或展开时,会导致父 Expander 升起它的 Expanded
或 Collapsed
事件。
有谁知道这是为什么或者我该如何改变它?我只对父母的事件感兴趣。
这是一些测试 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>
这是隐藏代码:
private void Expander_Expanded(object sender, RoutedEventArgs e)
{
MessageBox.Show("expanded");
}
private void Expander_Collapsed(object sender, RoutedEventArgs e)
{
MessageBox.Show("collapsed");
}
当您运行此代码时,如果展开父项,您将得到一个“展开的”消息框,正如您所期望的那样。但是当您展开其中一个子项时,您会再次看到消息框。
Expanded 事件的文档显示:
当 IsExpanded 属性从 false 变为 true 时,将发生 Expanded 事件
但显然 IsExpanded 属性在父 Expander 上没有更改。
为什么会发生这种情况,有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这些事件被路由并在树中冒泡,如果您想阻止父级处理事件并对其做出反应,请将
e.Handled
设置为true
子扩展器的事件处理程序。编辑:您也可以将处理程序中的代码执行限制为附加处理程序的实际扩展器引发事件时的情况,而不是阻止引发事件。您可以通过将所有内容包装在
if
块中来执行此操作,该块执行 ifsender == e.OriginalSource
。(哇,一万...)
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
totrue
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 ifsender == e.OriginalSource
.(Woo, 10k...)