简体   繁体   English

将项目添加到Silverlight ComboBox

[英]Adding Item to Silverlight ComboBox

I have a Silverlight application with a ComboBox that is filled by VideoCaptureDevice 's. 我有一个Silverlight应用程序,其中包含由VideoCaptureDevice填充的ComboBox

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: XAML代码:

    <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>

Your explicitly setting the ItemsSource in the code behind and the XAML, choose one or the other. 您在后面的代码和XAML中显式设置了ItemsSource ,请选择其中一个。 Ideally you would take the XAML approach and set the DataContext appropriately. 理想情况下,您将采用XAML方法并适当地设置DataContext

Once you make that decision you can insert an item within your ComboBox by using the Items property. 做出决定后,您可以使用Items属性在ComboBox插入一个项目。

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. 更好的方法是利用ICollectionView并简单地对数据进行排序,然后让UI相应地进行响应。 Your ItemsSource would then be bound to the ICollectionView . 然后,您的ItemsSource将绑定到ICollectionView

You can easily insert an item at a desired index location in the Items collection of the ComboBox using the following code. 您可以使用以下代码轻松地在ComboBox的Items集合中的所需索引位置插入项目。

         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: 设置所选索引将默认情况下将ComboBox设置为显示您添加的项目:

   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... 我希望它将对您有帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM