Adding dynamic controls to Silverlight application after WCF Service Asynchronous Callback
I'm trying to add some dynamic controls to my Silverlight page after a WCF call. When I try to add a control to I get an error: Object reference not set to an instance of an object.
Here is a simplified version of my code:
using edm = SilverlightBusinessApplication.ServiceRefrence;
public partial class ListWCF : Page
{
edm.ServiceClient EdmClient = new ServiceClient();
public ListWCF()
{
EdmClient.GetTestCompleted += EdmGetTestComplete开发者_Go百科d;
EdmClient.GetTestAsync();
}
private void EdmGetTestCompleted(object sender, edm.GetTestCompletedEventArgs e)
{
//This is where I want to add my controls
Button b = new Button();
LayoutRoot.Children.Add(b); //Error: Object reference not set to an instance of an object
}
}
Is it not possible to modify the page after it has been loaded? What am I missing?
Thanks
Yes, it is possible to modify the page after it has been loaded.
The first thing you should do when you meet this kind of exception is to determine which of your variables are null. You should be able to do this via the debugger. Stick a breakpoint on this line of code (or tell VS to break when exceptions are thrown) and inspect the variables. My guess is that LayoutRoot is null.
I cannot see a call to InitializeComponent() in your class constructor. Within a Silverlight user control, this call will invoke the generated class that constructs your XAML and also locates the named elements (x:Name), allowing you to access them from your code.
精彩评论