繁体   English   中英

将MenuItem投射到绑定对象

[英]Cast MenuItem to the bound object

我在ContextMenu中有一个SubMenu,其中ItemSource设置为类似的表达式

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

当我处理来自ContextMenu的单击时,我有以下事件处理程序:XALM:

<ContextMenu MenuItem.Click="ContextMenu_Click">

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
        }

但是,即使OriginalSource是由MyObject类型的对象创建的,我也总是将其作为null。

我该怎么办?

您可以在处理程序中获取MenuItem实例,然后检查DataContext

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM