ListBox 에 Color 를 바인딩하고 Red 를 선택 및 스크롤하게 한다.

 

using System.Reflection;

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();

 

            Title = "List Color Names";

            // 윈도우의 목록처럼 ListBox를 생성

            ListBox listbox = new ListBox();

            listbox.Width = 150;

            listbox.Height = 150;

            listbox.SelectionChanged += ListBoxOnSelectionChanged;

            Content = listbox;

            // 색상명으로 ListBox를 채움

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

            foreach (PropertyInfo prop in props)

            {

                listbox.Items.Add(prop.Name);

            }

 

            listbox.SelectedItem = "Red";

            listbox.ScrollIntoView(listbox.SelectedItem);

            listbox.Focus();

        }

 

        void ListBoxOnSelectionChanged(object sender, SelectionChangedEventArgs args)

        {

            ListBox listbox = sender as ListBox;

            string str = listbox.SelectedItem as string;

            if (str != null)

            {

                Color clr = (Color)typeof(Colors).GetProperty(str).GetValue(null, null);

                Background = new SolidColorBrush(clr);

            }

        }

    }

}

 

 

 

 

+ Recent posts