WPF ComboBox(BrushPanel)

BrushPanel

BrushPanel

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows.Controls;

using System.Reflection;

using System.Windows.Media;

using System.Windows.Shapes;

using System.Windows;

 

namespace Quietwalk

{

    public class BrushPanel

    {

        static StackPanel[] brushPanel;

 

        static BrushPanel()

        {

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

            brushPanel = new StackPanel[props.Length];

            int i=0;

            foreach (PropertyInfo prop in props)

            {

                Color clr = (Color)prop.GetValue(null, null);

                bool isBlack = .222 * clr.R + .707 * clr.G + .071 * clr.B > 128;

             

                StackPanel sp = new StackPanel();

                sp.Orientation = Orientation.Horizontal;

                Rectangle rect = new Rectangle();

                rect.Width = 16;

                rect.Height = 16;

                rect.Fill = new SolidColorBrush(clr);

                rect.Margin = new Thickness(1);

                sp.Children.Add(rect);

 

                TextBlock tBlock = new TextBlock();

                tBlock.Margin = new Thickness(5, 0, 0, 0);

                tBlock.Text = prop.Name;

                sp.Children.Add(tBlock);

                sp.Tag = clr;

 

                brushPanel[i] = sp;

                i++;

            }

 

        }

 

        public static StackPanel[] Panel

        {

            get { return brushPanel; }

        }

    }

}

 

XAML

<ComboBox Name="cboxColoredLabel" Grid.Row="0" Grid.Column="3" 

                 VerticalAlignment="Center" HorizontalAlignment="Left" Width="150"

              

                 FontSize="12">

 

</ComboBox>

C# Code

this.cboxColoredLabel.ItemsSource = Quietwalk.BrushPanel.Panel;

this.cboxColoredLabel.SelectionChanged += cboxColoredLabelOnSelectionChanged;

 void cboxColoredLabelOnSelectionChanged(object sender, SelectionChangedEventArgs args)

        {

            ComboBox cBox = sender as ComboBox;

          

            StackPanel sp = cBox.SelectedItem as StackPanel;

            if (sp != null)

            {

                Color clr = (Color)sp.Tag;

                Background = new SolidColorBrush(clr);

            }

        }

原文地址:https://www.cnblogs.com/quietwalk/p/2440617.html