How to create an unbound combobox in Microsoft Ligthswitch?

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.

Advertisements
About

Software developer living in the Philippines.

Posted in Lightswitch
12 comments on “How to create an unbound combobox in Microsoft Ligthswitch?
  1. jdp says:

    Hi,

    What’s the purpose of

    cmbBranchId.SetBinding(System.Windows.Controls.ComboBox.SelectedItemProperty, “BranchId”, Windows.Data.BindingMode.TwoWay) ?

    I don’t understand why one has to define some handlers if the binding to get BranchId to be affected with the combobox selected item is already defined! By the way, I tried without defining the handlers and it doesn’t work. I’m now working on how to translate your code to c#…

    • hgminerva says:

      I have the same problem if I don’t define handlers.

      And as of the moment I still have a minor problem even with the handlers, the refresh screen is not working properly, I need to save the screen in order to refresh its content even if I already change the item in the combo box “weird”.

      But aside from that its working.

      Tell me if you have problems with the conversion, actually the original code is C# i just converted it to VB.net.

      • scafaria says:

        Thanks for the great code. I wonder if your problem on refresh is due to events getting added multiple times. I noticed that Screen_Created gets called again every time you Refresh. Setting a private variable _ditInit and setting to True when Screen_Created is called might help.

      • hgminerva says:

        Thanks for the input scafaria. Just to let you know I am not using anymore custom control, combo box, I am using auto complete box attached to a property.

  2. MP says:

    Hi,
    Can you send me the code in C#..

    Can we change too the .LostFocus event for another that work with change selection in the combobox.

    Thanks

  3. hgminerva says:

    Here is the sample C# code:

    =====

    private void CreateNewCustomer_Created()
    {
    this.FindControl(“Category”).ControlAvailable += CategoryFieldAvailable;
    }

    private void CategoryFieldAvailable(object sender, ControlAvailableEventArgs e)
    {
    ((System.Windows.Controls.Control)e.Control).LostFocus += CategoryFieldChanged;
    }

    private void CategoryFieldChanged(object sender, System.Windows.RoutedEventArgs e)
    {
    //Add a reference to System.Windows.Controls.Input.dll in the Client project
    string txtComboText = ((System.Windows.Controls.AutoCompleteBox)sender).Text;
    this.Details.Dispatcher.BeginInvoke(() =>
    {
    if (!string.IsNullOrEmpty(txtComboText)) {
    Category selectedCategory = this.DataWorkspace.ApplicationData.Categories.Where(Category => Category.CategoryName == txtComboText).FirstOrDefault;
    if (selectedCategory == null) {
    //Category doesn’t exists
    if (this.ShowMessageBox(“Do you want to add the category ” + txtComboText + “?”, “Add Category”, MessageBoxOption.YesNo) == System.Windows.MessageBoxResult.Yes) {
    selectedCategory = this.DataWorkspace.ApplicationData.Categories.AddNew();
    selectedCategory.CategoryName = txtComboText;
    this.CustomerProperty.Category = selectedCategory;
    }
    }
    }
    });

    }

    ======
    As for the Lost Focus event I have no alternative. Thats why right now I am converting my search combo box to the native lightswitch Auto complete box.

  4. hgminerva says:

    MP, thats the problem, some, I think almost all properties of the custom control combobox are not accessible through ligthswitch using setBinding properties through control proxy. That is why I converted all my custom control combobox into a native ligthswitch auto complete textbox. Anyways, I will do more experiment on control proxies.

  5. raj says:

    Unable to cast object of type ‘Microsoft.LightSwitch.Presentation.Implementation.Controls.BaseDataGridControl’ to type ‘System.Windows.Controls.AutoCompleteBox’.
    i get this error when make string txtComboText = ((System.Windows.Controls.AutoCompleteBox)sender).Text;

    • hgminerva says:

      I believe the Autocompletebox returns a record not a text.

      Do this instead:

      Dim branch As mstBranch = CType(sender, System.Windows.Controls.ComboBox).SelectedItem

      Dim branchName as String = mstBranch.BranchName

  6. Thanks so much for the helpful tutorial. I have a problem which I would greatly appreciate assistance with. This solution, or at least when I implement it, leaves the selected item on all records as the previously selected item. How would I clear the selected item once an option has been selected and saved in another attribute?

    Regards,
    Matt

  7. self storage says:

    Thanks for finally talking about >How to create
    an unbound combobox in Microsoft Ligthswitch?
    | Harold Glenn P Minerva <Liked it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Author

Harold Glenn P. Minerva
Software Developer / Tech Enthusiast
Living in the Philippines

View Harold Glenn Minerva's profile on LinkedIn

Instagram

Software Engineer - Seasonal and Range Trading Software. Magenta Trader is a powerful stock market visualization software that increases your probability of trading success.

Software Architect and Founder - Easyfis.com is a multi-tenant cloud-based Software-as-a-Service (SaaS) business app that caters to micro, small and medium trading businesses.

CTO and Co-Founder - We give your company the leverage by providing innovative software solutions products such as Point-of-Sales (POS), Financial Information System (FMIS), Payroll and DTR (HRIS), and many more.

%d bloggers like this: