Search code examples
wpfxamlcontextmenucode-behind

Context Menu is not displayed on first LeftClick


I have the followings:

<telerik:RadButton Name="AddButton" DockPanel.Dock="Right"
                   Content="Add" HorizontalAlignment="Right"
                   Click="AddButton_OnClick" Padding="5,0,5,0">
                                            <telerik:RadButton.ContextMenu>
                                                <ContextMenu x:Name="addContextMenu"
                                                    ItemsSource="{Binding Path=AvailableTypesToAdd}">
                                                    <ContextMenu.ItemTemplate>
                                                        <DataTemplate>
                                                            <MenuItem Header="{Binding Path=Name}"
                                                                      Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:RadExpander}}, Path=DataContext.AddCommand}"
                                                                      CommandParameter="{Binding}" />
                                                        </DataTemplate>
                                                    </ContextMenu.ItemTemplate>
                                                </ContextMenu>
                                            </telerik:RadButton.ContextMenu

In code behind I have the following:

private void AddButton_OnClick(object sender, RoutedEventArgs e)
    {
        AddButton.ContextMenu.PlacementTarget = this;
        AddButton.ContextMenu.IsOpen = true;
    }

However, when I LeftClick the context menu is empty, but if I right click it is populated. If I remove the PlacementTarget = this, if I rightclick first then it will be populated when I left click as well.

Any ideas ?


Solution

  • I found the fix. Instead of setting:

    AddButton.ContextMenu.PlacementTarget = this;
    

    set to:

    AddButton.ContextMenu.PlacementTarget = (UIElement)sender;