Menü Schließen

Creating ComboBox with System Colors in XAML

This snippet shows how to display a list of system colors in XAML only.

First we create ab object data source containing the list of colors:

<ObjectDataProvider ObjectInstance="{x:Type Colors}" MethodName="GetProperties" x:Key="ListOfColors" />

This data source obtains the list of colors from the properties of the Colors type.

In the next step we define a data template for the items. This is basically that because we want a rectangle with the current color displayed in front of the color name:

<DataTemplate x:Key="ColorTemplate">
  <Grid>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto"/>
      <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Border Background="{Binding Name}" BorderBrush="Black" Width="18" Height="18" />
    <TextBlock Text="{Binding Name}" Grid.Column="1" Margin="2"/>
  </Grid>
</DataTemplate>

Finally we use the ObjectDataProvider named ListOfColors as ItemsSource of a ComboBox:

<ComboBox ItemsSource="{Binding Source={StaticResource ListOfColors}}" ItemTemplate="{StaticResource ColorTemplate}" />

Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert