开发者

Add controls to contextual menu in WPF

开发者 https://www.devze.com 2023-03-30 15:46 出处:网络
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

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 开发者_Python百科Access have when click a on cell in a table, where you can filter by a textbox value.

Thanks.


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;
}
0

精彩评论

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

关注公众号