[WPF] ColorGridBox

C#/WPF 2020. 7. 6. 22:36
728x90
728x170

색상을 그리드 형태로 나열하여 선택 시 배경색이 바뀌는 코드입니다.

 

ColorGridBox.cs

using System.Collections.Generic;

using System.Reflection;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Controls.Primitives;

using System.Windows.Media;

using System.Windows.Shapes;

 

namespace WpfApp

{

    class ColorGridBox : ListBox

    {

        public ColorGridBox()

        {

            // ItemsPanel template 을 정의합니다.

            FrameworkElementFactory factoryUniformGrid = new FrameworkElementFactory(typeof(UniformGrid));

            // 10 개 컬럼을 갖도록 설정합니다.

            factoryUniformGrid.SetValue(UniformGrid.ColumnsProperty, 10);

            // template 을 ItemPanel 에 적용합니다.

            ItemsPanel = new ItemsPanelTemplate(factoryUniformGrid);

 

            // Color 이름을 가져옵니다.

            List<string> colorStringList = new List<string>();

            PropertyInfo[] propertyInfos = typeof(Colors).GetProperties();

            foreach (PropertyInfo propertyInfo in propertyInfos)

            {

                colorStringList.Add(propertyInfo.Name);

            }

 

            // Color 를 체웁니다.

            foreach (string colorString in colorStringList)

            {

                // 사작형으로 표시합니다.

                Rectangle rectangle = new Rectangle();

                rectangle.Width = 15;

                rectangle.Height = 15;

                rectangle.Margin = new Thickness(4);

                rectangle.Fill = (Brush)typeof(Brushes).GetProperty(colorString).GetValue(null, null);

 

                // ListBox 에 Add 합니다.

                Items.Add(rectangle);

 

                // 툴팁을 정의합니다.

                ToolTip toolTip = new ToolTip();

                toolTip.Content = colorString;

                rectangle.ToolTip = toolTip;

            }

 

            // Value 값을 사각형의 Fill 값으로 지정합니다.

            SelectedValuePath = "Fill";

        }

    }

}

 

 

 

 

MainWindow.xaml.cs

using System.Windows;

 

namespace WpfApp

{

    /// <summary>

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

    /// </summary>

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

 

            Title = "Select Color Grid";

 

            ColorGridBox colorGridBox = new ColorGridBox() { Width = 350, VerticalAlignment = VerticalAlignment.Center };

            colorGridBox.SetBinding(ColorGridBox.SelectedValueProperty, "Background");

            colorGridBox.DataContext = this;

 

            Content = colorGridBox;

        }

    }

}

 

 

 

 

728x90
그리드형
Posted by kjun
,