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


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


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}">
      <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="Brushes"/>
      </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>