在 WCF 服务异步回调之后向 Silverlight 应用程序添加动态控件
我正在尝试在 WCF 调用后向我的 Silverlight 页面添加一些动态控件。当我尝试添加控件时,出现错误:未将对象引用设置为对象的实例。
这是我的代码的简化版本:
using edm = SilverlightBusinessApplication.ServiceRefrence;
public partial class ListWCF : Page
{
edm.ServiceClient EdmClient = new ServiceClient();
public ListWCF()
{
EdmClient.GetTestCompleted += EdmGetTestCompleted;
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
}
}
加载页面后是否无法修改页面?我缺少什么?
谢谢
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 += EdmGetTestCompleted;
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,页面加载后可以对其进行修改。
当遇到这种异常时,您应该做的第一件事是确定哪些变量为空。您应该能够通过调试器来完成此操作。在这行代码上设置一个断点(或者告诉 VS 在抛出异常时中断)并检查变量。我的猜测是 LayoutRoot 为空。
我在类构造函数中看不到对 InitializeComponent() 的调用。在 Silverlight 用户控件中,此调用将调用生成的类来构造 XAML,并定位命名元素 (x:Name),从而允许您从代码中访问它们。
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.