[WPF] ContextMenu

C#/WPF 2020. 7. 8. 12:38
728x90
728x170

특정 컨트롤에 ContextMenu 를 만드는 방법입니다.

MainWindow.xaml

<Window x:Class="WpfApp.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        xmlns:local="clr-namespace:WpfApp"

        mc:Ignorable="d"

        Title="MainWindow" Height="400" Width="600">

    <TextBlock

 Name="txtblk"

 FontSize="24pt"

 HorizontalAlignment="Center"

 VerticalAlignment="Center"

 ToolTip="Right click to display context menu">

 TextBlock with Context Menu

        <TextBlock.ContextMenu>

            <ContextMenu MenuItem.Click="MenuItemOnClick">

                <MenuItem Header="Red" />

                <MenuItem Header="Orange" />

                <MenuItem Header="Yellow" />

                <MenuItem Header="Green" />

                <MenuItem Header="Blue" />

                <MenuItem Header="Indigo" />

                <MenuItem Header="Violet" />

            </ContextMenu>

        </TextBlock.ContextMenu>

    </TextBlock>

</Window>

 

 

MainWindow.xaml.cs

using System.Windows;

using System.Windows.Controls;

using System.Windows.Media;

 

namespace WpfApp

{

    /// <summary>

    /// MainWindow.xaml에 대한 상호 작용 논리

    /// </summary>

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }

 

        void MenuItemOnClick(object sender, RoutedEventArgs args)

        {

            string str = (args.Source as MenuItem).Header as string;

            Color clr = (Color)ColorConverter.ConvertFromString(str);

            txtblk.Foreground = new SolidColorBrush(clr);

        }

    }

}

 

 

 

728x90
그리드형
Posted by kjun.kr
,