开发者

Dynamically add User Controls to a Silverlight 4 page

I am building an iGoogle like "dashboard" for our application with silverlight 4.

Each users dashboard (which snapins and their positions) will be stored in the database. Each snap in is a user control, for example... AwesomeSnapin.xaml.

On the dashboard page in silverlight I am retrieving the users dashboard which is a collection of snapin objects which include the information on the snapin. I can store the name of the page or the class or whatever is needed.

I have the following code which loops through the collection of snapins to add them to the dashboard page. In testing I have just hard coded a single snapin item. He开发者_高级运维re is the prototype code:

        foreach (var UserSnapin in op.Entities)
        {
            UserControl uc = new AmsiSL.eFinancials.BudgetCheck();

            Canvas.SetLeft(uc, UserSnapin.PositionLeft);
            Canvas.SetTop(uc, UserSnapin.PositionTop);

            Layout.Children.Add(uc);

            MessageBox.Show(String.Format("Added {0}",UserSnapin.Snapin.Name));
        }  

The above works fine... but of course adds the BudgetCheck snapin for every item that is defined for the users dashboard. Of course the messagebox is for debugging purposes only.

How would I change line 3 of that to load the user control class (using classname or xaml path whichever is better) based on the data in the collection.


I'll assume for the moment that UserSnapin.Snapin.Name in this case is "BudgetCheck" and that all Snapins are found in the AmsiSL.eFinancials namespace. I'll also assume that your Usercontrols are compilied in to the same application assembly. You can use this code:-

    foreach (var UserSnapin in op.Entities)
    {
        Type snapInType = Assembly.GetExecutingAssembly()
          .GetType("AmsiSL.eFinancials." + UserSnapin.Snapin.Name);

        UIElement snapIn = (UIElement)Activator.CreateInstance(snapInType );

        Canvas.SetLeft(snapIn , UserSnapin.PositionLeft);
        Canvas.SetTop(snapIn , UserSnapin.PositionTop);

        Layout.Children.Add(snapIn);
    }

IF the snapins are an a library instead you can probably use the Type.GetType(string) static method to resolve the value for snapInType but you would need to know the assembly name as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜