Search code examples
c#silverlightvisual-studio-lightswitchfindcontrolautocompletebox

LightSwitch - getting an AutoCompleteBox with FindControl, becomes null on cast


I'm trying to access an AutoCompleteBox on one of my screens. I can see that FindControl() has located the control when I do var testControl = FindControl("MyControl");

However, when I attempt to cast this to the type of control it is supposed to be so I can manipulate it, the result is null.

This is what I'm doing:

System.Windows.Controls.AutoCompleteBox testBox = new System.Windows.Controls.AutoCompleteBox();
testBox = testControl as System.Windows.Controls.AutoCompleteBox;

testBox will be null.

It definitely says the control is an AutoCompleteBox on the screen, I'm not sure what I'm doing wrong. Can anyone help?

EDIT: Thanks to Yann, I was able to resolve this with the following code:

this.FindControl("MyControl").ControlAvailable += (p, e) =>
        {
            //For every  use I can just cast like ((System.Windows.Controls.AutoCompleteBox)e.Control)
        };

Solution

  • The object you get from FindControl is just a just proxy object, as you've discovered. The way to get at the real control is done in two steps:

    1. Add code to the screen's Created method (the control is not guaranteed to be available until the screen's Created method runs).
    2. Then add a handler to the proxy's ControlAvailable method.
    Private Sub ScreensName_Created
    
          FindControl("ControlsName"). AddressOf ControlsName_ControlAvailable
    
    End Sub
    
    Private Sub ControlsName_ControlAvailable(sender as Object, e as ControlAvailableEventArgs)
    
        'do whatever you want in here
        'you can cast e.Control to whatever is the type of the underlying Silverlight control.
    
    End Sub
    

    Of course, you need to replace "ScreensName" & "ControlsName" with your own names.

    (For some reason, I wasn't able to sucessfully format the entire text of two methods as code)