X
logo
Master your Data
8 May 2008

ComboBox / DropDownList for Silverlight 2.0

After playing around with Silverlight 2.0 which is pretty cool BTW. I noticed that there is no ComboBox control yet. So I thought it can't be that hard to get something working so here's how I done it.

The finished ComboBox in Silverlight

ComboBox

The XAML

(Note: I am using a graphic for the DropDown icon you could draw it but I didn't have time to try that!)

<UserControl x:Class="SilverlightApplication1.ComboBox"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel MouseLeftButtonDown="StackPanel_MouseLeftButtonDown">
        <StackPanel Orientation="Horizontal">
            <TextBox x:Name="MyTextBox" Height="18" FontSize="10" Text="ListBox" MinWidth="100"></TextBox>
            <Image Stretch="Fill" Source="dropdown.jpg" Width="10" />
        </StackPanel>
        <ListBox x:Name="MyControl" MaxHeight="100" Visibility="Collapsed" SelectionChanged="MyControl_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock FontSize="10" Text="{Binding}" />   
                </DataTemplate>               
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
</UserControl>

 

The Code Behind

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SilverlightApplication1
{
    public partial class ComboBox : UserControl
    {
        public ListBox TheList { get { return MyControl; } }

        public ComboBox()
        {
            InitializeComponent();
        }

        private void StackPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            if (MyControl.Visibility == Visibility.Visible)
            {
                MyControl.Visibility = Visibility.Collapsed;
            }
            else
            {
                MyControl.Visibility = Visibility.Visible;
            }
        }

        private void MyControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MyTextBox.Text = MyControl.SelectedItem.ToString();
        }
    }
}

 

Then on your main Silverlight Page just add something like this... (After you add the namespace right!)

<MyCtrls:ComboBox x:Name="xyz" Canvas.Left="400" Canvas.Top="50"></MyCtrls:ComboBox>

 

Now there is certainly room for improvement but this shows how easy it is to create your own controls in Silverlight.