Selasa, 03 September 2013

Bind ComboBox Control With Grid Resource: WPF

In my previous post, I have wrote about the combo box control and add some string items. In this article I will add a grid source and then bind that source to combo box control with some easy steps.

By default a grid is placed in the XAML code file of a window. Just add the below code in the grid snippet:
<Grid.Resources>          
<x:ArrayExtension Type="{ x:Type sys:String}" x:Key="cmbPlacesSource">
<sys:String>London</sys:String>
<sys:String>Italy</sys:String>
<sys:String>California</sys:String>
<sys:String>France</sys:String>
</x:ArrayExtension>
</Grid.Resources>

The above code is defining an array extension which will be used as a source of the combo box. Now add a combo box and it should be look like the following code:
<ComboBox Name="cmbPlaces" Height="30" Width="100"
 Text="Select Places-"
 IsEditable="True"
 ItemsSource="{StaticResource cmbPlacesSource}">
</ComboBox>
Here in the above code, it doesn’t matter of height and width, you can provide these as you want. The must thing is ItemsSource of the combobox. As you are looking the code it is the same name of the above array extension. It will show all the data defined in the above source i.e. as in following image:

ComboBox binding with Grid Resource in WPF

In above image by default "Select Places-" is shown, which can be set by the text property with IsEditable property to true. In the selection changed event of combo box, we can get the selected value by using the following code:
private void cmbBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedValue = cmbPlaces.Text;
MessageBox.Show(selectedValue);
}

Each time when the selection index will change, it will show a message box with the selected text. So we can easily get the selected text of the combo box.

Tidak ada komentar:

Posting Komentar