首页 > 代码库 > XAML技术:SilverLight中可编辑ComboBox的简易实现

XAML技术:SilverLight中可编辑ComboBox的简易实现

今天编程的时候要用到ComboBox控件,然而SilverLight中的ComboBox与平常所用的大不一样,无论怎么设置都实现不了编辑功能,所以想出了这个土方法,原理就是让ComboBox和TextBox位置上重叠,TextBox在上面。

具体实现操作如下:

1.在前台设计代码中添加ComboBox和TextBox控件,并给每个空间添加唯一标识Name

2.将ComboBox和TextBox进行绑定。

DataContext="{Binding ElementName=textBox1,Mode=OneTime}

3.为ComboBox添加事件:ComboBox_DropDownClosed

            <Canvas Margin="0,0,0,0">
                <ComboBox Height="23" Name="comboBox1" Width="120" DropDownClosed="ComboBox_DropDownClosed" DataContext="{Binding ElementName=textBox1,Mode=OneTime}">
                        <ComboBoxItem Content="列表1-1" />
                        <ComboBoxItem Content="列表1-2" />
                        <ComboBoxItem Content="列表1-3" />
                </ComboBox>
                <TextBox  Height="23" Name="textBox1" Width="100" Canvas.Left="0" Canvas.Top="0" />
             </Canvas>
            <Canvas Margin="0,30,0,0">
                    <ComboBox DataContext="{Binding ElementName=textBox2, Mode=OneTime}" DropDownClosed="ComboBox_DropDownClosed" Height="23" Name="comboBox2" Width="120">
                        <ComboBoxItem Content="列表2-1" />
                        <ComboBoxItem Content="列表2-2" />
                        <ComboBoxItem Content="列表2-3" />
                </ComboBox>
                <TextBox Height="23" Name="textBox2" Width="100" />
             </Canvas>
4.实现事件处理函数

        private void ComboBox_DropDownClosed(object sender, EventArgs e)
        {
            ComboBox cmb = sender as ComboBox;
            BindingExpression binding = cmb.GetBindingExpression(ComboBox.DataContextProperty);
            TextBox Txt = binding.DataItem as TextBox;
            ComboBoxItem cbi = cmb.SelectedItem as ComboBoxItem;
            if(cbi != null)
            	Txt.Text = cbi.Content.ToString();
        }
源码下载:SilverLight中可编辑ComboBox的简易实现.zip