开发者

Cast MenuItem to the bound object

I have a SubMenu in a ContextMenu which ItemSource is set to a expression like

ContextMenu.Items[i].ItemsSource = DatabaseInstance.GetAllObjects()

When i handle the clicks from the ContextMenu i have this event handler: XALM:

<ContextMenu MenuItem.Click="ContextMenu_开发者_如何学GoClick">

C#:

        if (e.OriginalSource as MyObject == null) {
            //Not MyObject. Choose action by comparing Header
        }
        else {
            // The clicked item is a MyObject, send to another method
        }

But even though the OriginalSource was created by an object of the type MyObject i always get is as a null.

How would i do this?


You can get the MenuItem instance in the handler and check the DataContext

if(((FrameworkElement)sender).DataContext is MyObject)
{
     // The clicked item is a MyObject, send to another method
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜