Creating a bounded combobox is a breeze using Microsoft Ligthswitch, you just have to make sure that your field that is bounded to your combobox is a foreign key. But what if you want to create an unbounded combobox that uses data from your database. At first I thought this was just a simple property settings to the native combobox being provided by Microsoft Lightswitch, I was dead wrong, whoa!. But after two days of tinkering I got it running and here are the steps.
1. Add two data items to your screen: one is the table that you wish to be shown in your combobox and the other is a public variable to which you want to store the selected choice once the user select an item in your combobox.
2. The next step is to add the combobox itself. (It is a custom control coming from System.Windows.Controls, see my Password Masked blog. for details)
3. Now that the combobox and the two data items are in place its time to write the codes: In your screen activated or initialized method add the following code snippet. The first three lines of the code are used to fill the combobox with data while the 4th and last line is to add an event handler declaration of the combobox (I notice that if I use a custom control in Microsoft Lightswitch I need to make an event handler..hmm…).
Dim cmbBranchId As IContentItemProxy = Me.FindControl("mstBranches") cmbBranchId.SetBinding(System.Windows.Controls.ComboBox.ItemsSourceProperty, "Screen.mstBranches",Windows.Data.BindingMode.TwoWay) cmbBranchId.SetBinding(System.Windows.Controls.ComboBox.SelectedItemProperty, "BranchId",Windows.Data.BindingMode.TwoWay) AddHandler cmbBranchId.ControlAvailable, AddressOf mstBranchesAvailable
4. Now add the event handler functions: Notice that the second function contains the dispatcher invocation that saves the selected Id in the combobox to the public variable that I declared in No. 1.
Private Sub mstBranchesAvailable(sender As Object, e As ControlAvailableEventArgs) AddHandler CType(e.Control, System.Windows.Controls.Control).LostFocus, AddressOf mstBranchesChanged End Sub Private Sub mstBranchesChanged(sender As Object, e As System.Windows.RoutedEventArgs) 'Add a reference to System.Windows.Controls.Input.dll in the Client project Dim branch As mstBranch = CType(sender, System.Windows.Controls.ComboBox).SelectedItem Me.Details.Dispatcher.BeginInvoke( Sub() BranchId = branch.Id End Sub) End Sub
Thats it! I know that this may look strange for a Microsoft Access developer but I really do not know how or what may be the other option to have an unbounded combobox in my application.