Zach L
Zach L

Reputation: 1275

Adding Item to Silverlight ComboBox

I have a Silverlight application with a ComboBox that is filled by VideoCaptureDevice's.

cbVideoDevices.ItemsSource = CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();

I'm trying to add item, "Select a video device" to the first index but I can't get it to work.

XAML Code:

    <ComboBox Height="25" HorizontalAlignment="Left" Margin="0,0,0,0" Name="cbVideoDevices" VerticalAlignment="Top" Width="125" ItemsSource="{Binding AudioDevices}" SelectedItem="{Binding SelectedAudioDevice}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding FriendlyName}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

Upvotes: 1

Views: 8348

Answers (2)

Aaron McIver
Aaron McIver

Reputation: 24713

Your explicitly setting the ItemsSource in the code behind and the XAML, choose one or the other. Ideally you would take the XAML approach and set the DataContext appropriately.

Once you make that decision you can insert an item within your ComboBox by using the Items property.

ComboBox box = new ComboBox();
box.Items.Insert(0, "My Item");

A better approach would be to leverage the ICollectionView and simply sort the data and let the UI respond accordingly. Your ItemsSource would then be bound to the ICollectionView.

Upvotes: 1

Glory Raj
Glory Raj

Reputation: 17701

You can easily insert an item at a desired index location in the Items collection of the ComboBox using the following code.

         TextBlock t = new TextBlock();
        t.Text = "Select a video device"
        combo.Items.Insert(0, t);

Setting the selected index will set the ComboBox to show your added item by default:

   combo.SelectedIndex = 0;

or

you can do like this..

   YourClassObject objSelectItem = new YourClassObject(); 
    objSelectItem.ID = "0"; 
    objSelectItem.Name = "Select Item"; 
    ComboBox1.Items.Insert(0,objSelectItem); 

i hope it will helps you...

Upvotes: 0

Related Questions