Rajnish Noonia

Tag: WPF

  • WPF Multithreading

    WPF have the concept of the UI thread and background (or secondary) threads. Code on a background thread is not allowed to interact with UI elements (controls, etc.) on the foreground thread.  What happens when you need to add and remove items from a collection from that background thread? That’s pretty common in applications which must keep a list updated . When the collection raises the change notification events, the binding system and listeners, on the UI thread, have code executed.

    Before WPF 4.5 we have to use dispatcher to enable this feature in observable collection or we end up creating thread safe observable collection and also expose Add Range function which is not available in observable collections.

    WPF 4.5 includes a number of key targeted performance and capability features, one of which is cross-thread collection change notification. Enabling the change notification is as simple as the inclusion of a lock object and a single function call. Versus the manual dispatching approach, this can be a real performance win, not to mention save you some coding time.

    Use BindingOperations.EnableCollectionSynchronization to enable this cross thread access of observable collections.

    So inside your view model you call this method and provide the lock to synchronise the collection from multiple threads. BindingOperations.EnableCollectionSynchronization, the WPF data binding engine participates in locking. The default behavior is to acquire a lock on the object specified in the aforementioned call, but you also have the option to use more complex locking schemes.

    something like

    BindingOperations.EnableCollectionSynchronization(this.items, itemsSyncLock);

    where

    private readonly object itemsSyncLock = new object();

    private readonly ObservableCollection<string> items = new ObservableCollection<string>();

    Now when you have to add data into collection from background thread

    simply lock the collection and update it

    lock (itemsSyncLock)
    {
    // Once locked, you can manipulate the collection safely from another thread
    items.Add(value);
    }

    This means now you don’t need IDispatcher in you application anymore..

    There are also other binding properties like IsAsync (to get the data asynchronously) , Delay (provides delay before committing binding values etc)..

  • ViewModel First – ViewCaching

    With View model first approach, view are usually created via DataTemplate, and each time a view model is injected in the content control, the corresponding view is recreated.

    If you have complex view where it take bit time to create view, you may see the performance hits. To avoid the performance hit you may want to cache the view and use the cached view when available. This can be done via creating CacheContentControl and you choice of view factory.

    The basic idea is to wrap the view inside CacheContentControl and delegate the view creation logic to your view factory. The attached sample uses weakreference view factory,say if GC has not collected the view, you may use the cached view instead of creating view each time. This will work with controls like tab control docking controls etc.

    The CacheContentControl  code

    public class CacheContentControl : ContentControl
        {
            public CacheContentControl()
            {
                Unloaded += ViewCache_Unloaded;
                ViewFactory = WeakReferenceViewFactory.Instance;
            }
    
            void ViewCache_Unloaded(object sender, RoutedEventArgs e)
            {
                Content = null;
            }
    
            private Type _contentType;
            public Type ContentType
            {
                get { return _contentType; }
                set
                {
                    _contentType = value;
                   //  use you favorite factory
                    Content = ViewFactory.GetView(value);
                }
            }
    
            public IViewFactory ViewFactory { get; private set; }
        }
    

    In the DataTemplate, use the ViewCache, pass the type of the real view you want to use:

    <DataTemplate DataType=”{x:Type moduleB:Panel3Vm}”>

    <Border Background=”Green”>

    <local:CacheContentControl ContentType=”{x:Type moduleB:Pane3 }” Margin=”5″/>

    </Border>

    </DataTemplate>

    The example uses standard data template (red option) to demonstrate each time you navigate to panes the corresponding views are recreated with new hash code.

    If you select CacheContentControl (green option) and navigate the view is only created once. If you click on button to collected the GC then view are created on navigation if they are claimed by GC.

    Why ViewModel first ?

    I prefer to use view model first approach. For many reasons:

    • Vms are your application containing most of logic apart from glue code in form of behaviors or triggers.
    • If you creates views then you are responsible for its life and cleanup code. You have to deal with threading and other issues which are difficult to test. On the other hand of you create vms and leave the view creation logic with WPF via data template.. you don’t have to worry about threading issue. And there will be better separation of concerns.
    • With vm first approach zero code behind.
    • With a project level isolation for view and vms you can restrict developers using view specific things like dispatcher in the view model leaving more cleaner and testable code base. I.e view project sprojec to vm. And vm project should not refer to any presentation lib.
    • If there is clear boundary between view and vm. Both can evolve and will be less fragile.
    • Allows more complete testing of logic to open new Views and ViewModels
    • Tends to be DRYer (don’t repeat yourself ) as applications get larger
    • View and ViewModel are more independent and can be worked on separately more easily.

    For more details see attached source code (download and rename docx to zip)

    Viewcache Source Code

  • Async Entity Framework for WPF

    – Sample application , implemented ObjectContext, – base class for your entity data modal classes in WPF project, where data is used via ADO.net instead of WCF. The extension adds Async capability to your existing entity data model ..This is based on .net 4.0 Task..The below mentioned approach is one way implementing Async entity call , wrapped inside thread call and finally exposed event when results are available.Another prefred approach to achive this is via Reactive Extension library.

    The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Using Rx, developers represent asynchronous data streams with Observables, query asynchronous data streams using LINQ operators, and parameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, Rx = Observables + LINQ + Schedulers.

     My next article is about Reactive Extensions for streaming data similar to SQL Server Management Studio.This way the grid would show first 100 available rows in the beginning and then when the next 100 rows were loaded they would be added to the grid and so on until the query completes.

    Create class ObjectContext

    public class ObjectContext :EntityContext, IDisposable
        {
            public LoadOperation LoadQuery(Action query)
            {
                return new LoadOperation(query);
            }
    
            public LoadOperation LoadQuery(Func<object> query)
            {
                return new LoadOperation(query);
            }
    
            public void Dispose()
            {
                //throw new NotImplementedException();
            }
        }
    
    public sealed class QueryResultEventArgs : EventArgs
        {
            internal QueryResultEventArgs(Exception exception)
            {
                this.Error = exception;
                this.HasError = true;
            }
    
            internal QueryResultEventArgs(Exception exception, bool isCancelled, bool isCompleted, bool hasError)
                : this(exception)
            {
                this.IsCanceled = isCancelled;
                this.IsComplete = isCompleted;
                this.HasError = hasError;
                /// if (hasError == false) this.Error = null;
    
            }
    
            internal QueryResultEventArgs(object result)
            {
                this.HasError = false;
                this.Result = result;
                this.IsComplete = true;
                this.IsCanceled = false;
            }
    
            public object Result { get; private set; }
            public Exception Error { get; private set; }
            public bool HasError { get; private set; }
            public bool IsCanceled { get; private set; }
            public bool IsComplete { get; private set; }
        }
    
        public sealed class LoadOperation : DispatcherObject, IDisposable
        {
            public event EventHandler<QueryResultEventArgs> Completed;
            private readonly CancellationTokenSource _taskCancelProvider;
            private readonly Task _task;
            private LoadOperation()
            {
                this._taskCancelProvider = new CancellationTokenSource();
            }
    
            internal LoadOperation(Func<object> query)
                : this()
            {
    
                Task<object> task = new Task<object>(query, this._taskCancelProvider.Token);
                _task = task;
                this.SetTaskInternal(task);
            }
    
            internal LoadOperation(Action query)
                : this()
            {
                Task task = new Task(query, this._taskCancelProvider.Token);
                _task = task;
                this.SetTaskInternal(task);
            }
    
            private void SetTaskInternal(Task<object> task)
            {
                task.ContinueWith(delegate
                {
                    try
                    {
                        RaiseCompletetionEvent(new QueryResultEventArgs(task.Result));
                    }
                    catch (Exception ex)
                    {
                        RaiseCompletetionEvent(new QueryResultEventArgs(ex.InnerException, task.IsCanceled, task.IsCompleted, task.IsFaulted));
    
                    }
                });
            }
    
            private void SetTaskInternal(Task task)
            {
                task.ContinueWith(delegate
                {
                    try
                    {
    
                        RaiseCompletetionEvent(new QueryResultEventArgs(null));
                    }
                    catch (Exception ex)
                    {
                        RaiseCompletetionEvent(new QueryResultEventArgs(ex));
    
                    }
                });
            }
    
            public bool CanCancel { get { return this._taskCancelProvider.Token.CanBeCanceled; } }
    
            public void Cancel()
            {
                this._taskCancelProvider.Cancel();
            }
    
            public void Cancel(bool throwOnFirstException)
            {
                this._taskCancelProvider.Cancel(throwOnFirstException);
            }
    
            private void RaiseCompletetionEvent(QueryResultEventArgs e)
            {
                //Wrap in DispatchThread
                this.Dispatcher.Invoke(
              System.Windows.Threading.DispatcherPriority.Normal,
              new Action(
                delegate()
                {
                    if (Completed != null)
                        Completed(this, e);
                }
            ));
    
            }
    
            public void Execute(bool Async = true)
            {
                if (Async)
                {
                    _task.Start();
                }
                else
                {
                    _task.RunSynchronously();
                }
            }
    
            public void Dispose()
            {
                _task.Dispose();
            }
        }
    
    // EntityContext - Base for all your entity classes (LocalEntities - generated by entity framework)
    
    public class EntityContext
        {
            public LocalEntities ObjectContext
            {
                get;
                private set;
            }
    
            public  EntityContext()
            {
                ObjectContext = new LocalEntities();
            }
        }
    
    // How to Executing Async load of data from entity (serviceUsersRepository is ObjectContext driven entity)
    
                serviceUsersRepository = new ServiceUsersRepository();
                LoadOperation result = serviceUsersRepository.LoadQuery(() => serviceUsersRepository.GetServiceUsers(objSearchCriteria.SearchText));
    
                result.Completed += ((object sensexSx, QueryResultEventArgs ex) =>
                {
                    this.AllServiceUsers = ex.Result as List<ServiceUser>;
                });
                result.Execute();
    
    // example of serviceUsersRepository is described below (where ServiceUsers is entity generated by entity framework)
    
    class ServiceUsersRepository : ObjectContext�
        {
            public ServiceUsersRepository()
            {
    
            }
    
            /// <summary>
            /// Returns a shallow-copied list of all Service Users in the repository.
            /// </summary>
            public List<ServiceUser> GetServiceUsers(string sText)
            {
                    var result = from serviceuser in ObjectContext.ServiceUsers
                                 select serviceuser;
                    return result.ToList<ServiceUser>();
            }
        }
  • Dependency Properties

    WPF introduces a new type of property called a dependency property, used throughout the platform to enable styling, automatic data binding, animation, and more. Definition of Dependency Properties on MSDN

    A dependency property depends on multiple providers for determining its value at any point in time. These providers could be an animation continuously changing its value, a parent element whose property value trickles down to its children, and so on. Arguably the biggest feature of a dependency property is its built-in ability to provide change notification. The motivation for adding such intelligence to properties is to enable rich functionality directly from declarative markup.

    Below is the demonstration of how Button effectively implements one of its dependency properties which is called IsDefault.

    public class Button : ButtonBase
    {
    // The dependency property
    public static readonly DependencyProperty IsDefaultProperty;
    static Button()
    {
    // Register the property
    Button.IsDefaultProperty = DependencyProperty.Register(“IsDefault”,
    typeof(bool), typeof(Button),
    new FrameworkPropertyMetadata(false,
    new PropertyChangedCallback(OnIsDefaultChanged)));
    …
    }
    // A .NET property wrapper (optional)
    public bool IsDefault
    {
    get { return (bool)GetValue(Button.IsDefaultProperty); }
    set { SetValue(Button.IsDefaultProperty, value); }
    }
    // A property changed callback (optional)
    private static void OnIsDefaultChanged(
    DependencyObject o, DependencyPropertyChangedEventArgs e) { … }
    …
    }

    The static IsDefaultProperty field is the actual dependency property, represented by the System.Windows.DependencyProperty class. By convention all DependencyProperty fields are public, static, and have a Property suffix.

    So one of the first things I thought was weird about the definition of a dependency property is that it is a static. This property needs to store info relevant to a particular instance of a class, how is it going to do that if it is static?

    As you read more about them, you will realized that a dependency property definition was exactly that – a definition. You are essentially saying that class A will have a property B – and it makes sense that that definition would be static. The actual storage of a value for a dependency property is deep inside the WPF property system – you never have to worry about it.

    Dependency properties are usually created by calling the static DependencyProperty.Register method, which requires a name (IsDefault), a property type (bool), and the type of the class claiming to own the property

    (Button). Optionally (via different overloads of Register), you can pass metadata that customizes how the property is treated by WPF, as well as callbacks for handling property value changes, coercing values, and validating values. Button calls an overload of Register in its static constructor to give the dependency property a default value of false and to attach a delegate for change notifications.

    Finally, the traditional .NET property called IsDefault implements its accessors by calling GetValue and SetValue methods inherited from System.Windows.DependencyObject, a low-level base class from which all classes with dependency properties must derive. GetValue returns the last value passed to SetValue or, if SetValue has never been called, the default value registered with the property.

    So at first glance, all the properties on the new WPF controls seem to be regular old properties. But don’t be fooled – this is often just a simple wrapper around a dependency property.

    The IsDefault .NET property (sometimes called a property wrapper) is not strictly necessary; consumers of Button could always directly call the GetValue/SetValue methods because they are exposed publicly. But the .NET property makes programmatic reading and writing of the property much more natural for consumers, and it enables the property to be set via XAML.

    GetValue and SetValue internally use an efficient sparse storage system and because IsDefaultProperty is a static field (rather than an instance field), the dependency property implementation saves per-instance memory compared to a typical .NET property. If all the properties on WPF controls were wrappers around instance fields (as most .NET properties are), they would consume a significant amount of memory because of all the local data attached to each instance. The benefits of the dependency property implementation extend to more than just

    memory usage, however. It centralizes and standardizes a fair amount of code that property implementers would have to write to check thread access, prompt the containing element to be re-rendered, and so on.

    Change Notification

    Whenever the value of a dependency property changes, WPF can automatically trigger a number of actions depending on the property’s metadata. These actions can be re-rendering the appropriate elements, updating the current layout, refreshing data bindings,and much more. One of the most interesting features enabled by this built-in change notification is property triggers, which enable you to perform your own custom actions when a property value changes without writing any procedural code.

    For example, imagine that you want the text in each Button to turn blue when the mouse pointer hovers over it. Without property triggers,you can attach two event handlers to each Button, one for its MouseEnter event and one

    for its MouseLeave event:

    <Button MouseEnter=”Button_MouseEnter” MouseLeave=”Button_MouseLeave”
    MinWidth=”75” Margin=”10”>Help</Button>
    <Button MouseEnter=”Button_MouseEnter” MouseLeave=”Button_MouseLeave”
    MinWidth=”75” Margin=”10”>OK</Button>

    These two handlers could be implemented in a C# code-behind file as follows:

    // Change the foreground to blue when the mouse enters the button
    void Button_MouseEnter(object sender, MouseEventArgs e)
    {
    Button b = sender as Button;
    if (b != null) b.Foreground = Brushes.Blue;
    }
    // Restore the foreground to black when the mouse exits the button
    void Button_MouseLeave(object sender, MouseEventArgs e)
    {
    Button b = sender as Button;
    if (b != null) b.Foreground = Brushes.Black;
    }

    With a property trigger, however, you can accomplish this same behavior purely in XAML. The following concise Trigger object is (just about) all you need:

    <Trigger Property=”IsMouseOver” Value=”True”>
    <Setter Property=”Foreground” Value=”Blue”/>
    </Trigger>

    This trigger can act upon Button’s IsMouseOver property, which becomes true at the same time the MouseEnter event is raised and false at the same time the MouseLeave event is raised. Note that you don’t have to worry about reverting Foreground to black when IsMouseOver changes to false. This is automatically done by WPF! You could apply the preceding Trigger to a Button by wrapping it in a few intermediate XML elements as follows:

    <Button MinWidth=”75” Margin=”10”>
    <Button.Style>
    <Style TargetType=”{x:Type Button}”>
    <Style.Triggers>
    <Trigger Property=”IsMouseOver” Value=”True”>
    <Setter Property=”Foreground” Value=”Blue”/>
    </Trigger>
    </Style.Triggers>
    </Style>
    </Button.Style>
    OK
    </Button>
    Three type of triggers are available in WPF

    Property Triggers : As mentioned above

    A data trigger is a form of property trigger that works for all .NET properties (not just dependency properties)

    An event trigger enables you to declaratively specify actions to take when a routed event. Event triggers always involve working with animations or sounds

    Property Value Inheritance

    The term property value inheritance or property inheritance doesn’t refer to traditional object oriented class based inheritance, but rather the flowing of property values down the element tree.

    Example :

    <Window xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    
    Title=”Property Inheritance sample” SizeToContent=”WidthAndHeight”
    
    FontSize=”30” FontStyle=”Italic”
    
    Background=”OrangeRed”>
    
    <StackPanel>
    
    <Label FontWeight=”Bold” FontSize=”20” Foreground=”White”>
    
    WPF Property Inheritance
    
    </Label>
    
    <Label>Rajneesh</Label>
    
    <Label>Tech</Label>
    
    <ListBox>
    
    <ListBoxItem>.Net</ListBoxItem>
    
    <ListBoxItem>C#</ListBoxItem>
    
    </ListBox>
    
    <StackPanel Orientation=”Horizontal” HorizontalAlignment=”Center”>
    
    <Button MinWidth=”75” Margin=”10”>Cancel</Button>
    
    <Button MinWidth=”75” Margin=”10”>OK</Button>
    
    </StackPanel>
    
    <StatusBar>You have successfully created property inheritance</StatusBar>
    
    </StackPanel>
    
    </Window>
    

    Note : Window automatically resizes to fit all the content thanks to its slick SizeToContent setting!

    In above example we are explicitly setting window FontSize and FontStyle dependency properties.

    For the most part, these two settings flow all the way down the tree and are inherited by children. This affects even the Buttons and ListBoxItems, which are three levels down the logical tree. The first Label’s FontSize does not change because it is explicitly marked with a FontSize of 20, overriding the inherited value of 30.

    Note : Internally, dependency properties can opt in to inheritance by passing FrameworkPropertyMetadataOptions. Inherits to DependencyProperty.Register

    Support for Multiple Providers

    WPF contains many powerful mechanisms that independently attempt to set the value of dependency properties.

    Attached Properties

    An attached property is a special form of dependency property that can effectively be attached to arbitrary objects.

    Imagine that rather than setting FontSize and FontStyle for the entire Window (in above example), you would rather set them on the inner StackPanel so they are inherited only by the two Buttons. But StackPanel doesn’t have any font-related properties of its own! Instead, you must use the FontSize and FontStyle attached properties that happen to be defined on a class called TextElement.

    <StackPanel TextElement.FontSize=”30” TextElement.FontStyle=”Italic”
    Orientation=”Horizontal” HorizontalAlignment=”Center”>
    <Button MinWidth=”75” Margin=”10”>Cancel</Button>
    <Button MinWidth=”75” Margin=”10”>OK</Button>
    </StackPanel>

    Just like previous technologies such as Windows Forms, many classes in WPF define a Tag property (of type System.Object) intended for storing arbitrary custom data with each instance. But attached properties are a more powerful and flexible mechanism for attaching custom data to any object deriving from DependencyObject. It’s often overlooked that attached properties enable you to effectively add custom data to instances of sealed classes.

    *Beginners : I would like to recommended WPF fundamental tutorials by Christian Moser at http://www.wpftutorial.net

  • WPF Introduction

    The Windows Presentation Foundation (or WPF) is a graphical subsystem for rendering user interfaces in Windows-based applications. WPF, was initially released as part of .NET Framework 3.0. Designed to remove dependencies on the aging GDI subsystem, WPF is built on DirectX, which provides hardware acceleration and enables modern UI features like transparency, gradients and transforms. WPF provides a consistent programming model for building applications and provides a clear separation between the user interface and the business logic.

    WPF also offers a new markup language, known as XAML which is an alternative means for defining UI elements and relationships with other UI elements. A WPF application can be deployed on the desktop or hosted in a web browser. It also enables rich control, design, and development of the visual aspects of Windows programs. It aims to unify a number of application services: user interface, 2D and 3D drawing, fixed and adaptive documents, advanced typography, vector graphics, raster graphics, animation, data binding, audio and video.

    Microsoft Silverlight is a web-based subset of WPF that enables Flash-like web and mobile applications with the same programming model as .NET applications. 3D features are not supported, but XPS and vector-based drawing are included.

    It is compatible with multiple web browser products used on Microsoft Windows, Linux (using Novell Moonlight), Mac OS X operating systems & Mobile devices.

    WPF is designed to allow you to create dynamic, data driven presentation systems. Every part of the system is designed to create objects through property sets that drive behavior. Data binding is a fundamental part of the system, and is integrated at every layer.

    Traditional applications create a display and then bind to some data. In WPF, everything about the control, every aspect of the display, is generated by some type of data binding. The text found inside a button is displayed by creating a composed control inside of the button and binding its display to the button’s content property.

    Display technology evolution on windows …

    • User32 : Standard controls like buttons, textbox etc. This provides the windows look and feel for buttons and textboxes and other UI elements. User32 lacked drawing capabilities. Window forms are using User32 to render several controls including .net 2.0,vb, vc++ etc.
    • GDI (Graphics device interface) : Abstract graphics of drawing from hardware’s like printers ,monitors etc. Microsoft introduced GDI to provide drawing capabilities. GDI not only provided drawing capabilities but also provided a high level of abstraction on the hardware display. In other words it encapsulates all complexities of hardware in the GDI API. Several GDI API are available in windows platform to perform custom drawing. Hooks like subclassing cab be used to override default drawing of win32 controls on windows Or developers can create custom controls and use GDI API’s to render on screen.
    • GDI+ : JPG, PNG Image support, gradient shading, Anti Alising. GDI+ was introduced which basically extends GDI and provides extra functionalities like jpg and PNG support, gradient shading and anti-aliasing. The biggest issue with GDI API was it did not use hardware acceleration and did not have animation and 3D support. Object oriented approach to flat GDI+ API’s are available in .net which internally based on GDI+.
    • DirectX : Targeted for game programmers, Hardware  Acceleration (is a process in which we use hardware to perform some functions rather than performing those functions using the software which is running in the CPU.),support for animation,3D support, full colour graphics, Capture and play streaming media. One of the biggest issues with GDI and its extension GDI+ was hardware acceleration and animation support. This came as a biggest disadvantage for game developers. To answer and server game developers Microsoft developed DirectX. DirectX exploited hardware acceleration, had support for 3D, full color graphics , media streaming facility and lot more.
    • WPF : Based on direct (internally), support for primitive objects like text, shapes, controls etc, declarative UI using XAML, support for audio , video formats, define styles and templates for UI elements.  DirectX had this excellent feature of using hardware acceleration. Microsoft wanted to develop UI elements like textboxes,button,grids etc using the DirectX technology by which they can exploit the hardware acceleration feature. As WPF stands on the top of directX you can not only build simple UI elements but also go one step further and develop special UI elements like Grid, FlowDocument, and Ellipse. Oh yes you can go one more step further and build animations.WPF is not meant for game development. DirectX still will lead in that scenario. In case you are looking for light animation ( not game programming ) WPF will be a choice. You can also express WPF using XML which is also called as XAML.In other words WPF is a wrapper which is built over DirectX.

     The figure shows the overall architecture of WPF. It has three major sections presentation core, presentation framework and milcore.

     User32 :  It decides which goes where on the screen. User32 is used to determine what program gets what real estate. As a result, it’s still involved in WPF, but it plays no part in rendering common controls.

    • DirectX : WPF uses directX internally. DirectX talks with drivers and renders the content.
    • Milcore :  Mil stands for media integration library. This section is a unmanaged code because it acts like a bridge between WPF managed and DirectX / User32 unmanaged API. The composition engine in milcore is extremely performance sensitive, and required giving up many advantages of the CLR to gain performance. Milcore.dll is the core of the WPF rendering system and the foundation of the Media Integration Layer (MIL). Its composition engine translates visual elements into the triangle and textures that Direct3D expects. Though milcore.dll is considered a part of WPF, it’s also an essential system component for Windows Vista. The Desktop Window Manager (DWM) in Windows Vista uses milcore.dll to render the desktop.
    • Presentation core :– This is a low level API exposed by WPF providing features for 2D , 3D , geometry etc.,  includes base types, such as UIElement and Visual, from which all shapes and controls derive.
    • Presentation framework :  This section has high level features like application controls , layouts . Content etc which helps you to build up your application. The vast majority of Windows Presentation Foundation developers will work exclusively with this layer.
    • *Red colour box indicate WPF layer.

     

    Silverlight : WPF on web – platform independence

    The Silverlight runtime plug-in is essentially a ‘micro’ version of the .NET CLR. This runtime is hosted�
    within the client side browser. This runtime will host your Silverlight assemblies, as well as the Silverlight base class libraries. This runtime will JIT CIL code, handle threads, exceptions and garbage collection. This is a good thing, as your current .NET programming skills apply directly to Silverlight development.

    In addition to the ‘micro-CLR’, Silverlight supports a subset of the .NET base class libraries. When a�
    requesting browser loads a Silverlight page, any required assemblies are downloaded to the user’s machine, if they are currently not installed. Like any other .NET program, you can build your own code custom libraries for use within your Silverlight programs.

    A Silverlight application is deployed from a web server as an ‘XAP’ (zip file) package. The XAP file contains the compiled Silverlight assembly, any embedded resources, and any referenced assemblies. The Silverlight runtime downloads the XAP package and executes its contents in web browser.

    Once loaded by the plug-in, the SL application is able to make remote calls (to the web server or any arbitrary endpoint) using WCF technologies. The entire web page does *not* need to be refreshed when the SL web plug in changes state. This can greatly enhance the end user experience.

    Silverlight architecture is altogether different that WPF, however it tries to implement the features available in WPF. From developer prospective there is no major difference in WPF or Silverlight even though Silverlight CLR is not same as WPF CLR.