Get Microsoft Silverlight

Thursday, November 01, 2007

Show all the System.Windows.Media.Colors using DataBinding

Here is a sample to show all the Colors or even Brushes of WPF System.Windows.Media.Colors class.

<ListBox ItemsSource="{Binding Mode=OneWay, Source={StaticResource helper}}"  ItemTemplate="{DynamicResource DataTemplate1}"/>

Bellow is a function which gives all of its properties as PropertyInfo Collection.(If anybody out here knows a way to eliminate the use of this Helper class, please point that here)

public class Helper
    public PropertyInfo[] GetPropNames(Type type)
        return type.GetProperties();

Now you can write an ObjectDataProvider in XAML to call this function and then a DataTemplate to bind the PropertyName to the approapriate Dependancy Property. See the XAML

    <ObjectDataProvider x:Key="helper" MethodName="GetPropNames" ObjectType="{x:Type local:Helper}">
        <x:Type TypeName="Colors"/>
    <DataTemplate x:Key="DataTemplate1">
      <StackPanel Orientation="Horizontal">
        <Rectangle Width="40" Height="28" Fill="{Binding Name}" Stroke="#FF000000"/>
        <TextBlock  Text ="{Binding Name}" Foreground="{Binding Name}" />

Now if you need to show Brushes class members just need to replace Colors from the XAML with Brushes as shown here

    <ObjectDataProvider x:Key="helper" MethodName="GetPropNames" ObjectType="{x:Type local:Helper}">
        <x:Type TypeName="Brushes"/>


Anonymous said...


MMOB said...

Very helpful. Thank you for posting this. I have a question though. I have an object with a 'Fill' property which is a brush that I would like to bind to a 'combobox version' of this control. How do I get the 'Name' to match up with a 'Brush'? Do I need a converter?

Jobi Joy said...

That depends on where you are binding Fill from. If the source is originally the Colors collection then there will be a name associated with it and you can use the same trick which I used(Like Colors it works with System.Windows.Media.Brushes collection too.). But not all Brushes(like #FF123456) have name. Hope you got me.

ADmin said...

However there are this site courses to switch this pessimism into positive things.