David Brunelle
David Brunelle

Reputation: 6450

Add controls to contextual menu in WPF

I would like to add some contextual menu to some controls a in WPF project. This in itself is easy enough. I was wondering if it was possible to have controls like textbox or datepicker in them, much like Access have when click a on cell in a table, where you can filter by a textbox value.

Thanks.

Upvotes: 1

Views: 2003

Answers (1)

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84674

You can put whatever you like inside a ContextMenu, not only MenuItems. I never thought about it but I guess you could use it as a Popup when someone right click it. You can also add events etc.

<StackPanel>
    <StackPanel.Resources>
        <ContextMenu x:Key="myContextMenu">
            <StackPanel>
                <TextBox Text="Some Text.."/>
                <DatePicker/>
                <Button Content="Click Me" Click="Button_Click"/>
            </StackPanel>
        </ContextMenu>
    </StackPanel.Resources>
    <TextBox Text="Display some controls on right click"
             ContextMenu="{StaticResource myContextMenu}"/>
    <TextBox Text="Display some controls on right click"
             ContextMenu="{StaticResource myContextMenu}"/>
</StackPanel>

Get the clicked UIElement in the event handler

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button button = sender as Button;
    StackPanel stackPanel = button.Parent as StackPanel;
    ContextMenu contextMenu = stackPanel.Parent as ContextMenu;
    UIElement elementWithMenu = contextMenu.PlacementTarget;
}

Upvotes: 2

Related Questions