Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c# - How do I automatically adopt the MenuItemIcon as a button header when I select it for more then 1 Button?

So I already have it so that when I click on a MenuItem field on my last button ContextMenu, the content is automatically adopted as the content for the button. Here is the code:

MenuItem menuItem = (MenuItem)sender;
TextBlock textBlock = menuItem.Icon as TextBlock;

if (textBlock != null)
{
    // clone the TextBlock if you don't want to remove it from the MenuItem
    AlterMenuButton.Content = new TextBlock()
    {
        Text = textBlock.Text,
        FontSize = 8,
        Margin = textBlock.Margin,
        FontWeight = textBlock.FontWeight
    };
}

"AlterMenuButton" is the name of my Button. But now I have several buttons, each with its own context menu, how do I manage to use this one MenuItem_Click event to make this function for all of my buttons?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should work:

Button button = (menuItem.Parent as ContextMenu)?.PlacementTarget as Button;

Usage:

MenuItem menuItem = (MenuItem)sender;
TextBlock textBlock = menuItem.Icon as TextBlock;
Button button = (menuItem.Parent as ContextMenu)?.PlacementTarget as Button;
if (textBlock != null && button != null)
{           
    button.Content = new TextBlock()
    {
        Text = textBlock.Text,
        FontSize = 8,
        Margin = textBlock.Margin,
        FontWeight = textBlock.FontWeight
    };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...