Just something that someone asked me about today so sharing here. Imagine that you want to define a portion of your Silverlight application but leave some other piece to run time.
For example-a calculation engine or perhaps something more complicated like a piece of UI with interaction.
You can dynamically load up a. Net assembly in Silverlight at runtime, pull out known types from it and interact with them just like you wocould in any other. NET application.
I made my example as simple as possible. I defined a core UI which looks like this;
The idea is that the red bit is the "host" and the yellow bit is for the plug-in editor. I define an interface to live between my host and my plug-in editor;
Public ClassTexteventargs: eventargs {Public StringThetext {Get; Set ;}}Public InterfaceIeditui {uielement getcontrols ();VoidSettext (StringText );EventEventhandler <texteventargs> textchanged ;}
And then an implementation of that which I put into an assembly calledImplementationWhich isNot referenced by my Silverlight application.
Public Class Editor: ieditui { Public Editor () {textbox = New Textbox ();} Public Uielement getcontrols () {stackpanel = New Stackpanel (); stackpanel. Margin = New Thickness (5); stackpanel. Orientation = orientation. Horizontal; textbox = New Textbox (); textbox. width = 100; button = New Button (); button. content = "Click me" ; Button. Click + = onbuttonclick; stackpanel. Children. Add (textbox); stackpanel. Children. Add (button ); Return (Stackpanel );} Void Onbuttonclick ( Object Sender, routedeventargs e ){ If (Textchanged! = Null ) {Textchanged ( This , New Texteventargs () {thetext = textbox. Text });}} Public Void Settext ( String Text) {textbox. Text = text ;} Private Textbox; Public Event Eventhandler <texteventargs> textchanged ;}
Then, at runtime I can write code which will load this up and make use of it as in;
Public Partial Class Page: usercontrol { Public Page () {initializecomponent ();} Void Onloaddynamiceditor ( Object Sender, eventargs ARGs) {WebClient client = New WebClient (); client. openreadcompleted + = New Openreadcompletedeventhandler (onassemblyopened); client. openreadasync ( New Uri ( "Implementation. dll" , Urikind. Relative ));} Void Onassemblyopened (Object Sender, openreadcompletedeventargs e) {assemblypart = New Assemblypart (); Assembly = assemblypart. Load (E. Result); Editor = assembly. createinstance ( "Implementation. Editor" ) As Ieditui; If (Editor! = Null ) {Hostgrid. Children. Add (editor. getcontrols (); editor. textchanged + = oneditortextchanged ;}} Void Onsendtoeditor ( Object Sender, eventargs ARGs ){ If (Editor! = Null ) {Editor. settext (txthost. Text );}} Void Oneditortextchanged ( Object Sender, texteventargs e) {txthost. Text = E. thetext;} ieditui editor ;}
Note: The implementation. dll Assembly needs to be manually copied to the clientbin folder of the website project in order for this to work.