在代码中使用自己的用户控件填充Wrappanel

本文关键字:用户 控件 填充 Wrappanel 自己的 代码 | 更新日期: 2023-09-27 18:16:29

我试图创建一个页面,您可以在其中获得项目赞助商的概述,数据是从数据库中获取以下服务:

    [OperationContract]
    public IEnumerable<Sponsor> getSponsors()
    {
        var query = (from p in dc.Sponsors select p);
        IEnumerable<Sponsor> i = query;
        return i;
    }

当我把断点放在I上时,我可以看到数据在那里是正确的。

在我的Sponsorspage中,我做以下操作

public partial class Sponsorspage : UserControl
{
    IEnumerable<Sponsor> sponsors = null;

    public Sponsorspage()
    {
        SponsorsServiceClient client = new SponsorsServiceClient();
        client.getSponsorsCompleted +=new EventHandler<getSponsorsCompletedEventArgs>(client_getSponsorsCompleted);
        client.getSponsorsAsync();
        InitializeComponent();

    }
    void client_getSponsorsCompleted(object sender, getSponsorsCompletedEventArgs e)
    {
        if (e.Error != null)
            MessageBox.Show(e.Error.ToString());
        else
        {
            sponsors = e.Result;
            foreach (Sponsor s in sponsors)
            {
                SponsorView control = new SponsorView(s.tekst);
                SLWrapPanel.Children.Add(control);
            }
        }
    }

对于数据库中的每个赞助商,我创建Sponsorview,并为其提供源和文本。你可以在这里看到我的Sponsorview的代码。

public partial class SponsorView : UserControl
{
    public SponsorView(string tekst)
    {
        txtSponsor.Text = tekst;
        //Uri uri = new Uri(imageSource, UriKind.Relative);
        //ImageSource imgSource = new BitmapImage(uri);
        //imgSponsor.Source = imgSource;
        InitializeComponent();
    }
}

但是当我运行页面时,我得到以下错误:

Object reference not set to an instance of an object.
   at OndernemersAward.Views.SponsorView..ctor(String tekst)
   at OndernemersAward.Views.Sponsorspage.client_getSponsorsCompleted(Object sender, getSponsorsCompletedEventArgs e)
   at OndernemersAward.SponsorsServiceReference.SponsorsServiceClient.OngetSponsorsCompleted(Object state)

我要做的是给信息(这里是string tekst)从sponsor s到我的用户控件,然后它用来填充一个文本块。我做错了吗?

谢谢!:)

在代码中使用自己的用户控件填充Wrappanel

好吧,你试图迭代的结果,你应该保持在sponsors变量。但是,请注意,您调用的是getSponsors方法的异步版本(我记得这是Silverlight中唯一可用的版本)。它的意思是,你不会在调用service方法后立即得到结果,而是需要等待,直到完成执行的事件被调用。

我不知道为什么这样的东西会在调试时产生一些问题,但它肯定是代码中的错误,可能会导致显示页面的问题。

这是一个关于如何从服务中检索结果的简单示例。