WPF ListBox 属性绑定

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Reflection;

using System.Windows.Media;

 

namespace Quietwalk

{

    public class NamedBrush

    {

        static NamedBrush[] nbrushes;

 

        Brush brush;

        public Brush Brush

        {

            get { return brush; }

        }

 

        string name;

        public string Name

        {

            get

            {

                string strSpace = name[0].ToString();

                for (int i = 1; i < name.Length; i++)

                {

                    strSpace += (char.IsUpper(name[i]) ? " " : "") + name[i].ToString();

                }

                return strSpace;

            }

        }

 

        private NamedBrush(string str, Brush brush)

        {

            this.name = str;

            this.brush = brush;

        }

 

        static NamedBrush()

        {

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

            nbrushes = new NamedBrush[props.Length];

 

            for (int i = 0; i < props.Length; i++)

            {

                nbrushes[i] = new NamedBrush(props[i].Name,(Brush)props[i].GetValue(null, null));

            }

        }

 

        public static NamedBrush[] All

        {

            get { return nbrushes; }

        }

 

        public override string ToString()

        {

            return name;

        }

    }

}

<ListBox Name="lsBoxNamedBrush" Grid.Row="0" Grid.Column="1"  Grid.RowSpan="10"

                 VerticalAlignment="Center" HorizontalAlignment="Left"

                 SelectedValuePath="Brush" DisplayMemberPath="Name"

                 FontSize="17" Width="200">

           

</ListBox>

 

 private void Window_Loaded(object sender, RoutedEventArgs e)

        {

       

            this.lsBoxNamedBrush.ItemsSource = Quietwalk.NamedBrush.All;

 

            //Bind SelectedValue of ListBox to this.Background, here the this is the window.

            this.lsBoxNamedBrush.SetBinding(ListBox.SelectedValueProperty, "Background");

            this.lsBoxNamedBrush.DataContext = this;

        }

 

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