Reputation: 1410
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)
};
Upvotes: 2
Views: 2293
Reputation: 3879
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:
Created
method (the control is not guaranteed to be available until the screen's Created
method runs).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)
Upvotes: 1
Reputation: 33139
If as
returns null, you're trying to cast to the wrong type. I oother words, testControl
is not of type AutoCompleteBox
.
Put a breakpoint on that second line and see what type testControl
really is at runtime.
Upvotes: 1