在ContextMenuOpening中找不到DataContext

时间:2014-05-20 15:25:20

标签: c# wpf contextmenu

我正在尝试为我的数据网格添加一个上下文菜单,该菜单将根据所选行显示某个菜单项标题。例如,如果该行未标记为删除,则会有一个菜单项“标记为删除”。否则会说“Unmark for deletion”。

我认为我没有正确设置ContextMenu的DataContext,因此我无法从所选行中获取信息。

 <DataGrid Grid.Row="0" Name="OrdersGrid"
                ItemsSource="{Binding Path=Orders}" IsSynchronizedWithCurrentItem="True"
                AutoGenerateColumns="False"
                SelectedItem="{Binding Path=CurrentlySelected,Mode=OneWayToSource}"
                ContextMenuOpening="AddItemHeader">
            <DataGrid.ContextMenu>
                <ContextMenu DataContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
                        <MenuItem Header="dummy"
                                  Click="MarkForDeletion">                                
                        </MenuItem>

private void AddItemHeader(object sender, ContextMenuEventArgs e)
    {
        Console.WriteLine("ContextMenuOpening fired.");

        FrameworkElement fe = e.Source as FrameworkElement;
        ContextMenu menu = fe.ContextMenu;


        if (menu == null)
        {
            Console.WriteLine("Menu not found!");
            return;
        }

        MenuItem menuItem = null;

        foreach (Object o in menu.Items) {
            if (o is MenuItem)
            {
                if ((string)(o as MenuItem).Header == "dummy")
                {
                    menuItem = o as MenuItem;
                }
            }         
        }

        if (menuItem == null) {
            Console.WriteLine("Item not found!");
            return;                
        }

        if (menu.DataContext == null)
        {
            Console.WriteLine("Data Context not found!");
            return; 
        }

        OrderModel selectedItem = menu.DataContext as OrderModel;

        if (selectedItem == null)
        {
            Console.WriteLine("Can't get order from row!");
            return;
        }

        if (selectedItem.MarkedForDeletion)
        {
            menuItem.Header = "Unmark for deletion";
        }
        else
        {
            menuItem.Header = "Mark for deletion";
        }
    }

输出:

ContextMenuOpening fired.
Data Context not found!

0 个答案:

没有答案