0
votes

I want to display an image and text in a Silverlight ComboBox. I found an example in WPF with a ItemTemplate showing colors by image and name. In Silverlight the same xml results in empty lines. So for every item there is a item generated, it just doesn't bind to the Name property. Does Silverlight need other binding than WPF ?

This is the sample:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        cmbColors.ItemsSource = typeof(Colors).GetProperties();
    }
}

XML

<UserControl x:Class="SilverlightColors.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel >
            <ComboBox Name="cmbColors" >
                <ComboBox.ItemTemplate  >
                    <DataTemplate  >
                        <StackPanel Orientation="Horizontal">
                            <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0,2,5,2"/>
                            <TextBlock Text="{Binding Name}"/>
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
        </StackPanel>
    </Grid>
</UserControl>
1

1 Answers

0
votes

Trying to set the Fill of a Rectangle by binding to the name of a Color won't work. The XAML does some special magic to get:

<Rectangle Fill="White" Width="16" Height="16" Margin="0,2,5,2"/>

to work. So while the "Name" property of PropertyInfo that's returned from GetProperties() is "Black", "white" or "Yellow", you can't use it directly. What you'll have to do is create a dictionary of names and Brushes and assign each one a different colour and then bind your combobox's DataSource to that.

This code works:

.cs:

var list = typeof(Colors).GetProperties();
var brushes = new Dictionary<string, SolidColorBrush>();
foreach (var colour in list)
{
    brushes.Add(colour.Name, new SolidColorBrush((Color)colour.GetValue(colour, null)));
}
cmbColors.ItemsSource = brushes;

XAML:

<ComboBox Name="cmbColors"
          VerticalAlignment="Center"
          HorizontalAlignment="Center">
    <ComboBox.ItemTemplate  >
        <DataTemplate  >
            <StackPanel Orientation="Horizontal">
                <Rectangle Fill="{Binding Value}" Width="16" Height="16" Margin="0,2,5,2"/>
                <TextBlock Text="{Binding Key}"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>