Listen to child MenuItem Click

戏子无情 提交于 2019-12-01 11:13:57

问题


Is there a way for a parent MenuItem to be notified when a child MenuItem is pressed. For example, I you have

<MenuItem Name='a'>
    <MenuItem Name='b' Header='...'/>
</MenuItem>

how can I add an event handler to a to be notified when b is clicked. Ideally, the Click event would be either a tunnel or bubble event but this is not the case. The solution I have in mind is to listen to the Click event on b and forward it to a but this seems pretty heavy handed. Is there a better solution?


回答1:


MenuItem.Click is a routed event (it bubbles up), so you can just subscribe to it on the first MenuItem and be notified of all children at the same time.

XAML:

<MenuItem Name='a' Click='OnMenuItemClicked'>
    <MenuItem Name='b' Header='...' />
</MenuItem>

C#:

private void OnMenuItemClicked(object sender, RoutedEventArgs e)
{
    MenuItem item = e.OriginalSource as MenuItem;
    if(null != item)
    {
        // Handle the menu item click here
    }
}

The trick is to use RoutedEventArgs.OriginalSource, rather than sender. This points to the control that originally fired the event.



来源:https://stackoverflow.com/questions/1099546/listen-to-child-menuitem-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!