European Silverlight Hosting BLOG

BLOG about Latest Silverlight Hosting and Its Techologies - Dedicated to European Windows Hosting Customer

Silverlight 6 Hosting - HostForLIFE :: Graphics Path in Silverlight

clock March 1, 2024 07:54 by author Peter

Working with Path in Silverlight
A graphics path is a collection of connected lines, curves, and other basic graphic elements. This article explains how to utilize Path control in Silverlight with XAML and C#.

A graphics path is a collection of connected lines, curves, and other basic graphics objects including rectangles, ellipses, and text. A path functions as a single graphics object, thus any effect applied to the path affects all of its components. For example, if we draw a graphical path with a red stroke and it contains a line, a rectangle, and an ellipse, the red stroke will be applied to all three components of the path.
 
The Path object represents a path shape and creates a path. The Path object can create both closed and open pathways. A closed path is a shape with the same start and endpoints, whereas an open path has different starts and ends.
 
The Fill attribute fills the inside of an ellipse. StrokeThickness represents the width of an ellipse's outside line, whereas Stroke specifies its color.
 
The Path object's Data attribute defines a shape or group of forms in the form of Geometry.
 
The Path element represents a Silverlight path control in XAML.

<Path/>  

The code snippet in Listing 1 creates a Path and draws an arc by settings its Data property.
<Path Stroke="Black" StrokeThickness="4"   
    Data="M 80,200 A 100,50 45 1 0 100,50" /> 

The Path Syntaxes
Let us take a look at the Data attribute of the Path code used in the previous section.
<Path Stroke="Black" StrokeThickness="4"   
        Data="M 80,200 A 100,50 45 1 0 100,50" />  


As you may see from the above code snippet, the Data attribute has the letter M followed by two comma-separated numbers, letter A is followed by two comma-separated numbers, and letter O is also followed by two comma-separated numbers.

The letter M represents a move action and moves to the given point from the current point. For example, M 80,200 command moves from the current point to the point (80, 200).

  • The letter L draws a line from the current point to the specified point. For example, the L 100,200 command draws a line from the current point to the point (100, 200).
  • The letter H draws a horizontal line from the current point to the specified point towards the x-axis.
  • The letter V draws a vertical line from the current point to the specified point towards the y-axis.
  • The letter C draws a cubic Bezier curve from the current point to the third point and two points in between are used as the control points.
  • The letter S draws a smooth cubic Bezier curve from the current point to the second point and the first point is used as the control point.
  • The letter Q draws a quadratic Bezier curve from the first point to the second point and the first point is used as the control point.
  • The letter T draws a smooth quadratic Bezier curve from the first point to the second point and the first point is used as the control point.
  • The letter A draws an elliptical arc. It takes five parameters -  Size, IsLargeArc, Rotation Angle, Sweep Direction, and Endpoint.
  •  The letter Z closes the current path by drawing a line from the current point to the starting point.

Using Geometries within a Path
The LineGeometry class represents the geometry of a line. The StartPoint and EndPoint properties of the LineGeometry class define the start and endpoints of a line. The following code snippet creates the geometry of a line.
<LineGeometry StartPoint="20,50" EndPoint="200,50" />  

The RectangleGeometry class represents the geometry of a rectangle. The Rect property of the RectangleGeometry defines the starting points, width, and height of a rectangle. The following code snippet creates the geometry of a rectangle.
<RectangleGeometry Rect="80,167 150 30"/>  

The EllipseGeometry class represents the geometry of an ellipse. The Center property of the EllipseGeometry defines the center of an ellipse. The RadiusX and RadiusY define the width and height of an ellipse. The following code snippet creates the geometry of an ellipse.
<EllipseGeometry Center="80,150" RadiusX="50" RadiusY="50" />  

The GeometryGroup creates a composite geometry that is a combination of multiple Geometry objects.

The code listed in Listing 2 creates a GeometryGroup with three geometry shapes - a line, an ellipse, and a rectangle and sets the Data property of a path.
<Path Stroke="Black" StrokeThickness="3" Fill="Blue" >  
    <Path.Data>  
        <GeometryGroup >  
            <LineGeometry StartPoint="20,200" EndPoint="300,200" />  
            <EllipseGeometry Center="80,150" RadiusX="50" RadiusY="50" />  
            <RectangleGeometry Rect="80,167 150 30"/>  
        </GeometryGroup>  
    </Path.Data>  
</Path>  


The output of Listing 2 looks like Figure 2

The FillRule attribute of the GeometryGroup class determines how the intersecting areas of geometry objects in a GeometryGroup are mixed. It has two values: EvenOdd and Nonzero.  The FillRule's default value is EvenOdd. In this situation, the area where two shapes overlap is not filled. In the case of NonZero, the interesting space between two shapes is filled. Figure 3 is generated by adjusting the FillRule to nonzero.

Create a Path Dynamically
The code listed in Listing 3 creates Figure 2 dynamically. As you can see from Listing 3, we create a LineGeometry, an EllipseGeometry, and a RectangleGeometry and then we create a GroupGeometry and add all three geometries to the GroupGeometry. After that, we simply set the Data property of Path to the GroupGeometry.
    /// <summary>  
    /// Creates a blue path with black stroke  
    /// </summary>  
    public void CreateAPath() {  
        // Create a blue and a black Brush  
        SolidColorBrush blueBrush = new SolidColorBrush();  
        blueBrush.Color = Colors.Blue;  
        SolidColorBrush blackBrush = new SolidColorBrush();  
        blackBrush.Color = Colors.Black;  
      
        // Create a Path with black brush and blue fill  
        Path bluePath = new Path();  
        bluePath.Stroke = blackBrush;  
        bluePath.StrokeThickness = 3;  
        bluePath.Fill = blueBrush;  
      
        // Create a line geometry  
        LineGeometry blackLineGeometry = new LineGeometry();  
        blackLineGeometry.StartPoint = new Point(20, 200);  
        blackLineGeometry.EndPoint = new Point(300, 200);  
      
        // Create an ellipse geometry  
        EllipseGeometry blackEllipseGeometry = new EllipseGeometry();  
        blackEllipseGeometry.Center = new Point(80, 150);  
        blackEllipseGeometry.RadiusX = 50;  
        blackEllipseGeometry.RadiusY = 50;  
      
        // Create a rectangle geometry  
        RectangleGeometry blackRectGeometry = new RectangleGeometry();  
        Rect rct = new Rect();  
        rct.X = 80;  
        rct.Y = 167;  
        rct.Width = 150;  
        rct.Height = 30;  
        blackRectGeometry.Rect = rct;  
      
        // Add all the geometries to a GeometryGroup.  
        GeometryGroup blueGeometryGroup = new GeometryGroup();  
        blueGeometryGroup.Children.Add(blackLineGeometry);  
        blueGeometryGroup.Children.Add(blackEllipseGeometry);  
        blueGeometryGroup.Children.Add(blackRectGeometry);  
      
        // Set Path.Data  
        bluePath.Data = blueGeometryGroup;  
      
        LayoutRoot.Children.Add(bluePath);  
    }  


If we need to generate a single geometry, we do not need to use a GeometryGroup. We can simply set geometry as the Data of the Path. The following code snippet sets an EllipseGeometry as the Data property of a Path.
    <Path Stroke="Black" StrokeThickness="3" Fill="Blue" >  
        <Path.Data>              
                <EllipseGeometry Center="80,150" RadiusX="50" RadiusY="50" />  
       </Path.Data>  
    </Path>  

Formatting a Path
We can use the Fill property of the Path to draw a Path with any kind of brush including a solid brush, linear gradient brush, radial-gradient brush, or an image brush. The code in Listing 4 uses linear gradient brushes to draw the background and foreground of a Path.
    <Path Stroke="Black" StrokeThickness="3">  
        <Path.Data>  
            <GeometryGroup>  
                <LineGeometry StartPoint="20,200" EndPoint="300,200" />  
                <EllipseGeometry Center="80,150" RadiusX="50" RadiusY="50" />  
                <RectangleGeometry Rect="80,167 150 30" />  
            </GeometryGroup>  
        </Path.Data>  
        <Path.Fill>  
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">  
                <GradientStop Color="Blue" Offset="0.25" />  
                <GradientStop Color="Orange" Offset="0.50" />  
                <GradientStop Color="Green" Offset="0.65" />  
                <GradientStop Color="Red" Offset="0.80" />  
            </LinearGradientBrush>  
        </Path.Fill>  
    </Path> 


The new Path looks like Figure 4.

Setting Image as Background of a Path
To set an image as the background of a Path, we can set an image brush as the Fill of the Path. The code in Listing 5 sets fills the Path with an image.  
    <Path.Fill >  
        <ImageBrush ImageSource="dock.jpg" />  
    </Path.Fill > 


The new output looks like Figure 5.

 
Drawing a Semi-transparent Path
The Opacity property represents the transparency of a Path. The value of Opacity is between 0 and 1, where 0 is fully transparent and 1 is fully opaque. The code listed in Listing 6 generates a semi-transparent shape.
<Path Stroke="Black" StrokeThickness="3" Opacity="0.5" />  

The new output looks like Figure 5.

 



Silvelight 6 Hosting - HostForLIFE :: Working with DataGrid in Silverlight

clock March 31, 2023 07:46 by author Peter

Silverlight DataGrid Control
This article shows you how to work with a DataGrid control available in Silverlight 2.0. The article also demonstrates some formatting and data binding techniques.

Introduction
The DataGrid tag represents a Silverlight DataGrid control in XAML.  The DataGrid control is found in System.Windows.Controls namespace. When you drag and drop a DataGrid control from Toolbox to your XAML code, the action adds the following tag for the DataGrid control.
<my:DataGrid></my:DataGrid>  

And at the top of the XAML file, the designer adds the following line that adds a namespace System.Windows.Controls and assembly reference to System.Windows.Controls.Data.
xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  

The Width and Height attributes represent the width and height of a DataGrid.  The x: Name attribute represents the name of the control, which is a unique identifier of a control.  The Margin attribute sets the margin of the DataGrid being displayed from the top left corner.
 
The following code snippet sets the name, height, width, and margin of a DataGrid control.
    < my: DataGrid x: Name = "McDataGrid"  
    Width = "400"  
    Height = "300"  
    Margin = "10,10,10,10" > </my:DataGrid>  

Another way to create a DataGrid control is by dragging a DataGrid control from Toolbox to the XAML code in Visual Studio XAML editor.  Once you drag and drop a DataGrid control to the XAML page, you will see the following namespace reference is added to the XAML code.
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"    

And the following code is added to the XAML code for the DataGrid.
<data:DataGrid></data:DataGrid>  

Figure 1 shows Toolbox and XAML code preview after a DataGrid is added to a page.

Data Binding
The ItemSource property of DataGrid is the key to data binding. You can bind any data source that implements IEnuemerable. Each row in the DataGrid is bound to an object in the data source and each column in the DataGrid is bound to a property of the data source objects.
 
Listing 1 sets the ItemsSource property of a DataGrid to an array of strings.
    public MainPage() {  
      InitializeComponent();  
      McDataGrid.ItemsSource = LoadStringData();  
    }  
      
    /// <summary>  
    /// Load a string collection  
    /// </summary>  
    /// <returns></returns>  
    private string[] LoadStringData() {  
      return "One Two Three Four Five Six Seven Eight".Split();  
    }

Figure 2 is the result of Listing 1. As you may see from Listing 1, the default column of the DataGrid shows all the strings in the array.

This was a simple example. Now let's build a little complex example.
 
ItemsSource and Data Binding
In this example, we will create a collection of objects and bind it to a DataGrid control.
 
First, we are going to add a class to the project. Right click on the project, select Add New Item and select Class. I give my class name Author.cs. After that, we are going to add some public properties to the class. The simplest way to add a property to a class is type "prop" and hit TAB twice. This action will add an automatic property to the class. See Figure 3.

The final Author class looks like Listing 2.
    public class Author {  
      public int ID {  
        get;  
        set;  
      }  
      public string Name {  
        get;  
        set;  
      }  
      public DateTime DOB {  
        get;  
        set;  
      }  
      public string BookTitle {  
        get;  
        set;  
      }  
      public bool IsMVP {  
        get;  
        set;  
      }  
    }


Now let's create a collection of Author objects by using the List class. The LoadCollectionData method in Listing 3 creates a List of Author objects.
     /// <summary>  
    /// List of Authors  
    /// </summary>  
    /// <returns></returns>  
    private List<Author> LoadCollectionData()  
    {  
        List<Author> authors = new List<Author>();  
        authors.Add(new Author(){  
                ID = 101,  
                Name = "Peter",  
                BookTitle = "Graphics Programming with GDI+",  
                DOB = new DateTime(1975, 2, 23),  
                IsMVP = false });  
        authors.Add(new Author()  
        {  
            ID = 201,  
            Name = "Scott",  
            BookTitle = "Programming C#",  
            DOB = new DateTime(1982, 4, 12),  
            IsMVP = true  
        });  
        authors.Add(new Author()  
        {  
            ID = 244,  
            Name = "Mark",  
            BookTitle = "LINQ in Vista",  
            DOB = new DateTime(1985, 9, 11),  
            IsMVP = true  
        });  
        return authors;  
    }  


The following code snippet sets the ItemsSource property of a DataGrid to List of Authors.
    McDataGrid.ItemsSource = LoadCollectionData();  


The new DataGrid looks like Figure 4, which shows the properties of the Author class column names.

As you saw in Figure 4, all public properties of the Author object are represented as columns of the DataGrid. This is because by default, the AutoGenerateColumns property of DataGrid is true. If you do not wish to generate automatic columns, you simply need to set this property to false.
McDataGrid.AutoGenerateColumns = false;  

Setting Column Width and Row Height
The ColumnWidth and RowHeight properties of DataGrid are used to set the default column width and row height of DataGrid columns and rows.
 
The following code snippet sets column width and row height to 100 and 40 respectively.
 <data:DataGrid x:Name="McDataGrid" Width="580" Height="270"  
                   Margin="10,10,0,0" Background="Bisque"  
                   ColumnWidth="100" RowHeight="40">             
         
    </data:DataGrid>  

The new DataGrid looks like Figure 5.

The MaxWidth and MaxHeight properties represent the maximum width and maximum height of a DataGrid.  The MinWidth and MinHeight properties represent the minimum width and maximum height of a DataGrid. The MaxColumnWidth and MinColumnWidth properties represent the maximum width and minimum width of columns in a DataGrid.
 
Grid Lines Visibility and Header Visibility
The GridLinesVisibility property is used to make gridlines visible. Using this option you can show and hide vertical, horizontal, all, or none lines.  The HeaderVisibility property is used to show and hide row and column headers.
 
The following code snippet makes vertical grid lines visible and header visible for both rows and columns.
GridLinesVisibility="Vertical" HeadersVisibility="All"

The new DataGrid looks like Figure 6.


Grid Background, Row Background, and Alternative Row Background
The Background property is used to set the background color of the DataGrid. The RowBackground and AlternativeRowBackground properties are used to set the background color of rows and alternative of the DataGrid.
 
The following code snippet sets the background, row background, and alternative row background colors of a DataGrid.
Background="LightGray" RowBackground="LightYellow"
AlternatingRowBackground="LightBlue"  

The new DataGrid looks like Figure 7.


Border Color and Thickness
The BorderBrush and BorderThickness properties are used to set the color and width of the border. The following code snippet sets border color to gray and thickness to 5.
BorderBrush="Gray" BorderThickness="5"  

The DataGrid with a new border looks like Figure 8.

Sorting
By default, column sorting is enabled on a DataGrid. You can sort a column by simply clicking on the column header.  You may disable this feature by setting CanUserSortColumns property to false. The following code snippet sets CanUserSortColumns properties to false.
CanUserSortColumns = "False"  

Scrolling
The HorizontalScrollBarVisibility and VerticalScrollBarVisibility properties of type ScrollBarVisibility enumeration control the horizontal and vertical scrollbars of the DataGrid. It has four values - Auto, Disabled, Hidden, and Visible. The default value of these properties is Auto, that means, when scrolling is needed, you will see it, otherwise it will be hidden.
 
The following code snippet enables horizontal and vertical scrollbars.
    HorizontalScrollBarVisibility="Visible"  
    VerticalScrollBarVisibility="Visible"  


The DataGrid with both scrollbars looks like Figure 9.




Silvelight 6 Hosting - HostForLIFE :: CheckBox in Silverlight

clock January 11, 2023 07:48 by author Peter

Silverlight CheckBox Control

This article demonstrates how to create and use a CheckBox control in Silverlight with the help of XAML and C#.

Creating a CheckBox

The CheckBox element represents a Silverlight CheckBox control in XAML.

 

<CheckBox/>

 

The Content attribute represents the text of a CheckBox.  The x:Name attribute represents the name of the control, which is a unique identifier of a control. The code snippet in Listing 1 creates a CheckBox control and sets the name and content of a CheckBox control.

 

<CheckBox x:Name="McCheckBox"

          Canvas.Left="10" Canvas.Top="10"

          Content="Check Me" >            

</CheckBox>

The output looks like Figure 1.

The IsChecked property represents the state of the CheckBox control. The IsThreeState property represents whether the CheckBox has two or three states. Three states are checked, unchecked, or indeterminate.  The code snippet in Listing 2 sets IsChecked and IsThreeState properties of the CheckBox.

<CheckBox x:Name="McCheckBox"

          Canvas.Left="10" Canvas.Top="10"

          Content="Check Me"

          IsChecked="True" IsThreeState="True" >            

</CheckBox>

Listing 2

Adding a CheckBox Click Event Handler

The Checked and Unchecked attributes of the CheckBox element adds the checked and unchecked event handler. These events are fired when a CheckBox state is changed to checked and unchecked respectively. The code in Listing 3 adds these two event handlers.

<CheckBox x:Name="McCheckBox"

          Canvas.Left="10" Canvas.Top="10"

          Content="Check Me"

          IsChecked="True" IsThreeState="True"

          Checked="McCheckBox_Checked" Unchecked="McCheckBox_Unchecked">            

</CheckBox>

Listing 3

The code for the click event handler looks like following.

private void McCheckBox_Checked(object sender, RoutedEventArgs e)

{

}

 

private void McCheckBox_Unchecked(object sender, RoutedEventArgs e)

{

}

The code listed in Listing 4 sets a TextBox text on both checked and unchecked events.

private void McCheckBox_Checked(object sender, RoutedEventArgs e)

{

    McTextBox.Text = "Checked";

}

 

private void McCheckBox_Unchecked(object sender, RoutedEventArgs e)

{

    McTextBox.Text = "Unchecked";

}

Listing 4

Creating a CheckBox Dynamically

The code listed in Listing 5 creates a CheckBox control programmatically. First, it creates a CheckBox object and sets its width, height, contents, background and foreground and later the CheckBox is added to the LayoutRoot.

private void CreateDynamicCheckBox()

{

    CheckBox chb = new CheckBox();

    chb.Content = "Click me";

    chb.IsChecked  = true;

 

    LayoutRoot.Children.Add(chb);

}

Listing 5

Summary
In this article, I discussed how we can create a CheckBox control in Silverlight at design-time using XAML and at run-time using C#.



Silvelight 6 Hosting - HostForLIFE :: File Upload in Silverlight

clock November 29, 2022 06:56 by author Peter

In this article, I will discuss how you can create your own File Upload feature in a Silverlight application.

Step 1
First, create a Silverlight Web application in Visual Studio 2008. You will see your default Page.xaml.
 
Step 2
On Create Page.xaml, change your code by adding the following Panel, Button, and TextBlock controls.
On the button click event handler, I write code to call the OpenFileDialog that allows us to browse files and gives us the selected file name. Here is the code.
    public void Button_Click(object sender, RoutedEventArgs e) { 
      OpenFileDialog dlg = new OpenFileDialog(); 
      dlg.Multiselect = false; 
      dlg.Filter = "All files (*.*)|*.*|PNG Images (*.png)|*.png"; 
      bool ? retval = dlg.ShowDialog(); 
      if (retval != null && retval == true) { 
        UploadFile(dlg.File.Name, dlg.File.OpenRead()); 
        StatusText.Text = dlg.File.Name; 
      } 
      else { 
        StatusText.Text = "No file selected..."; 
      } 
    }

As you can see from the above code, I call a method UploadFile by passing the selected file name from the OpenFileDialog.
 
The UploadFile method looks like the following. In this code, I use a WebClient class and a PushData method.
    private void UploadFile(string fileName, Stream data) 
            { 
                UriBuilder ub = new UriBuilder("http://localhost:3840/receiver.ashx"); 
                ub.Query = string.Format("filename={0}", fileName); 
                WebClient c = new WebClient(); 
                c.OpenWriteCompleted += (sender, e) => 
                { 
                    PushData(data, e.Result); 
                    e.Result.Close(); 
                    data.Close(); 
                }; 
                c.OpenWriteAsync(ub.Uri); 
            } 
            private void PushData(Stream input, Stream output) 
            { 
                byte[] buffer = new byte[4096]; 
                int bytesRead; 
                while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0) 
                { 
                    output.Write(buffer, 0, bytesRead); 
                } 
            }

Step 3
Add a new Generic Handler receiver.ashx.
Now let's add a class. Right-click on the project and add a new item by selecting Generic Handler in the right side templates as shown below.

And add the following code on the code behind-
    <%@ WebHandler Language="C#" Class="receiver" %> 
     
    using System; 
    using System.Web; 
    using System.IO; 
    public class receiver : IHttpHandler { 
           public void ProcessRequest (HttpContext context) { 
            string filename = context.Request.QueryString["filename"].ToString(); 
            using (FileStream fs = File.Create(context.Server.MapPath("~/App_Data/" + filename))) 
            { 
                SaveFile(context.Request.InputStream, fs); 
            } 
        } 
        private void SaveFile(Stream stream, FileStream fs) 
        { 
            byte[] buffer = new byte[4096]; 
            int bytesRead; 
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) 
            { 
                fs.Write(buffer, 0, bytesRead); 
            } 
        } 
      
        public bool IsReusable { 
            get { 
                return false; 
            } 
        } 
    }


Step 4
Build and Run
That's all. You are done. Now just build and run your project.
When you click the Select File button, you will see Browse files dialog that lets you browse the files.

Note
You need to make sure your folder on the Web has to write permissions to upload files.
 
Summary
In this article, we learned about File Upload in Silverlight with an example.



Silvelight 6 Hosting - HostForLIFE :: MVVM Pattern

clock October 28, 2022 08:49 by author Peter

What is MVVM Pattern?
MVVM (Model-View-View Model) is the  design Pattern code model used for WPF/Silverlight UI. MVVM is the guideline a developer should follows in order to achieve a more testable, debug gable, manageable, readable Application.


MVVM is implemented with zero code behind.  Yes, no button click event hander in the code behind file, no form/windows load logic, no UI binding logic, and no UI validation or type casting code in the code behind file. Yes, I mean absolutely no code or logic in the UI mainpage.xaml.cs file.

The reason we don't want to put code-behind in our project is so that one can write a unit test against the code and create instances and run methods on our instances in a unit test.

The following features are used in order to achieve the MVVM pattern with no logic on the UI code behind file and to make sure that the presentation layer and logic remain loosely couple.
    Using the strong two-way binding capability of the WPF/Silverlight UI (through XAML)
    Implementing an IValueConvert for binding (eg: string converted to a Color instance, and also avoid type casting)
    Use INotification in our model or Dependency Property
    Set the data context at the xaml level
    Set Static resources at the xaml level
    ICommand for avoiding the code behind event handler.
    Use of validation=true in xaml(presentation layer)

Before MVVM, the MVP pattern was famous for its use in WinForm and WPF applications (it never took full advantage of the two-way binding feature of WPF).  The MVC pattern is still well-known for its use with Asp.net Application.

Below are some drawbacks of the old fashion WinForm or WPF/Silverlight applications that didn't leverage the power of the mvvm pattern.

    The presentation and the code behind logic is tightly coupled
    If we change the UI control we are forced to change the logic in the code behind
    It makes it hard to imagine a way of having more than one view sharing the same logic.
    It's not possible to write a unit test for a view that uses code behind because the presentation layer is tightly couple to the control.
    In previous practice with the WPF application, the view (xaml) often acted as a data store.

Advantages of MVVM pattern
    Proper layering of the view and the data. The data is not stored in the view, The view is just for presenting the data.
    Clean testable and manageable code.
    No code behind so the presentation layer and the logic is loosely coupled.
    With Silverlight 4.0 we have new ICommand Support (this was previously only present in the PRISM framework

    The architect design of the MVVM pattern is as follows:

    kindly visit http://www.elearningfromhome.com/Sample_Videos.php for more videos series on Silverlight and wcf videos.
    Also visit http://silverlightmvvm.blogspot.com

Step 1: Create a Silverlight Application in Viual studio 2010 and name it as "simplePersonandageMVVM"

Step 2: Once the project is created, add a class file and call it as "PersonModel.cs" and paste the code below. (this would be the model that represents the data object)

using System.ComponentModel;

namespace simplePersonandageMVVM
{
    public class PersonModel : INotifyPropertyChanged
    {
        string name;
        public string Name
        {
            get { return this.name; }
            set
            {
                this.name = value;
                fire("Name");
            }
        }

        int age;
        public int Age
        {
            get { return this.age; }
            set
            {
                this.age = value;
                fire("Age");
            }
        }

        public PersonModel() { }
        public PersonModel(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        public void fire(string x)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(x));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Step 3: Create another class call it as "PersonViewModel.cs" shown below. This class is the viewModel and serves as an adapter between view(presentation layer) and the Model(entity class).
namespace simplePersonandageMVVM
{
    public class PersonViewModel
    {
        public PersonModel p { get; set; }
        public PersonViewModel()
        {
            p = new PersonModel("prabjot", 20);                    
        }

        public ICommand GetPerson
        {
            get { return new GetPersonCommand(this); }
        }

        public void Increaseage(PersonModel d)
        {
            d.Age++;          
            string x = d.Age.ToString();          
            MessageBox.Show(x);      
        }
    }
}

Step 4: Create a Command object class implementing the ICommand interface and call it as "GetPersonCommand.cs". This class overrides two ICommand methods: Execute and CanExecute. The method CanExecute checks if the person's age is greater than 25 years old.  If the condition if its met, then only the button click is enabled. The Execute method takes care of execution upon clicking a the button.
namespace simplePersonandageMVVM
{
    public class GetPersonCommand : ICommand
    {
        PersonViewModel pincommand;
        public GetPersonCommand( PersonViewModel Pcame)
        {
          pincommand= Pcame;
        }

        public bool CanExecute(object parameter)
        {
           if(pincommand.p.Age > 25)
           {
               return false ;
           }
        else
           {
               return true;
           }
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
           pincommand.Increaseage(pincommand.p);
        }
    }
}

Step 5: Finally your xaml file looks like this:

    <UserControl x:Class="simplePersonandageMVVM.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:simplePersonandageMVVM"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <local:PersonViewModel  x:Key="pkey" />
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White"
          DataContext="{Binding Source={StaticResource pkey}}" >
        <Grid Name="hi" DataContext="{Binding Path=p, Mode=TwoWay}">
            <TextBox Height="23" HorizontalAlignment="Left" Margin="53,30,0,0"
                 Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=Name, Mode=TwoWay}" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="53,68,0,0" Name="textBox2"
                 Text="{Binding Path=Age, Mode=TwoWay}"  VerticalAlignment="Top" Width="120" />
            <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="53,112,0,0" Name="button1"
                VerticalAlignment="Top" Width="75"  Command="{Binding Path=DataContext.GetPerson, ElementName= LayoutRoot }"
                    CommandParameter="{Binding Path=Age, ElementName=hi}"  />
      </Grid>
    </Grid>
</UserControl>



 



Silvelight 6 Hosting - HostForLIFE :: Introduction To Silverlight in ASP.Net

clock June 16, 2022 08:44 by author Peter

Silverlight is a web-based technology that allows web designers and web developers to explore the boundaries of web application development.

It is an integration of rich user interface of desktop applications, where we use the HTML and JavaScript web languages. Silverlight helps in building web applications that contain high-fidelity multimedia content and eye-catching visual effects.  

We will make a simple Silverlight application in Visual Studio 10. Open Visual Studio 10. Create a New Project by pressing Ctrl + Shift + N, under C# go to Silverlight and choose Silverlight application. Name it Silverlight_demo.

This is your mainpage.xaml page where you will write your design code. It is very similar to a default .aspx page where we write design code in ASP.NET.

These are the main default files that exist when you create a new project.


 

This is your mainpage.xaml page code.

    < UserControl x: Class = "SilverlightApplication4.MainPage"  
    xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"  
    xmlns: d = "http://schemas.microsoft.com/expression/blend/2008"  
    xmlns: mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"  
    mc: Ignorable = "d"  
    d: DesignHeight = "300"  
    d: DesignWidth = "400" >  
      
    <Grid x: Name = "LayoutRoot"  
    Background = "White" > <TextBox Height = "60"  
    HorizontalAlignment = "Left"  
    Margin = "28,104,0,0"  
    Name = "textBox1"  
    Text = "Welcome here for getting Silverlight"  
    VerticalAlignment = "Top"  
    Width = "343"  
    FontWeight = "Bold"  
    Background = "#FF89FF89"  
    Foreground = "#FF1847D1"  
    Padding = "12"  
    FontSize = "15" / ></Grid>    
        </UserControl >  

The design will look like the following.

 Now open your MainPage.Xaml.cs page to make some server-side code for your textbook. Add your code after the InitializeComponent() in the constructor.
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Net;  
    using System.Windows;  
    using System.Windows.Controls;  
    using System.Windows.Documents;  
    using System.Windows.Input;  
    using System.Windows.Media;  
    using System.Windows.Media.Animation;  
    using System.Windows.Shapes;  
      
    namespace SilverlightApplication4 {  
      public partial class MainPage: UserControl {  
        public MainPage() {  
          // default constructor    
          InitializeComponent();  
          // we will add our textblock code here :    
          TextBlock txtn = new TextBlock() {  
      
            Name = "textBox1",  
            Text = "Welcome here for Getting Silverlight",  
            Foreground = new SolidColorBrush(Colors.Blue),  
      
          };  
      
        }  
      }  
    }


By pressing F5 you will get your output something like the following:



Silvelight 6 Hosting - HostForLIFE :: Duplexing in Silverlight

clock February 18, 2022 07:28 by author Peter

The idea of duplexing is very old, when I first read it, it reminded me about my Mom. Well actually not reminded me, but she never allowed me to even forget her, can you imagine 50 missed calls in a day!!! Annoyed . Okay, imagine you being a client and your Mom being the server. It's usually the client that starts communicating with server, requests for data, for authentication or for money, in this case. The server can either respond positively or negatively to the client's request. That is if your request is for money, then you either get it or don't, the later one usually happens in my case. Now what if the server initiates the communication? Yes! It's not always that the server listens to the client's request, but there are situations when the server also broadcasts the messages to all it's clients. This process is called Duplex polling. In Silverlight however, there are many ways to perform this server to client broadcasting, one way is through WCF Services that we are going to use now. So grab a cup of Coffee or two, because the journey is little bit lengthy and a bit complicated.

Before proceeding let's establish the strategy of what exactly we are going to do. What I planned is to keep it neat, clean and simple. So to start, let's create a Silverlight application first, naming it as MyPolling.

Now before going deep into WCF let's first set up our UI. It's nothing though, but a simple button and a text block. Here's how I arranged them in my XAML:

<UserControl x:Class="MyPolling.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Button x:Name="Start" Content="Send Message"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Click="Start_OnClick"/>
<TextBlock x:Name="TxtBlkInfo" Text="Press Button to start communication"
TextWrapping="Wrap" Width="200" Margin="0,0,200,251" />
</Grid>
</UserControl>

Looks cool isn't it? Okay, it's time to add some WCF stuff. On the web project "Add" -> "New item" -> "WCF Service" and name it "MyPollingService.svc". After clicking "Add" Visual Studio should have opened the "IMyPollingService" interface for you.


Delete the DoWork() function that is already in the interface. Now replace the interface with exactly the following lines of code:
public interface IMyPollingService
{
[OperationContract(IsOneWay = true)]
void SubmitResult(string rS);
}


It's time to make another interface, the client one, that will actually do the heavy lifting of taking the data from the server to the client. So, below the IMyPollingService interface, add the following lines:
[ServiceContract(CallbackContract = typeof(IMyPollingClient))]
public interface IMyPollingService
{
[OperationContract(IsOneWay = true)]
void SubmitResult(string rS);
}

Before wrapping up with the interface part, we need to make the service know about the existence of the client interface. In order to do so, just above the IMyPollingService interface add the following (line #1):
[ServiceContract(CallbackContract = typeof(IMyPollingClient))]
public interface IMyPollingService
{
[OperationContract(IsOneWay = true)]
void SubmitResult(string rS);
}

The interface part is ready, what we've done so far is we've structured our service for how our service is to look like, what will it contain etc. In a nutshell, we have created the overall contract of our service. Next is to grab another cup of Coffee.

So far, so good. It's time to open MyPollingService.svc.cs file. As you will see, there would be a class MyPollingService implementing the interface IMyPollingService that we just have modified. Therefore, it might have errors. So click on the implemented interface and implement the non-implemented methods. After that, if you have the SubmitResult method left in the class, then you are with me. Now we are going to send numbers from 1…100 to the client from the server. In order to do that we will use my love of loops, here's the code:
public void SubmitResult(string rS)
{
var client = OperationContext.Current.GetCallbackChannel<IMyPollingClient>();
for (var i = 0; i < 100; i++)
{
client.ReturnResult(i.ToString(CultureInfo.InvariantCulture));
Thread.Sleep(TimeSpan.FromSeconds(2));
}
}


Let's pause the coding for a few minutes and edit the configuration file, web.config. First we need to add the DLL System.ServiceModel.PollingDuplex.dll at the web side, to do this just right-click on refrences and browse to the following location: "C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Server" and add only the DLL present there. Similarly on the client side add the same DLL but from "C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Client". We are then ready for web.config's modifications.

Modifying Web.config is very simple. Let's take small steps to configure the file. The original file that we have presented with is:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
 -->

<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>

Step I
Naming behavior of the service
First we need to name the behavior of the service (line #16); let's set it to "BehaviourOfService":
<serviceBehaviors>
<behavior name="BehaviourOfService">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>


Step II
Setting custom binding for pollingduplex
Next we need to create the custom binding for pollingduplex so below the </behaviour> between lines #20 and #21 add the following:
<bindings>
<customBinding>
<binding name="pollingDuplexBinding">
<binaryMessageEncoding />
<pollingDuplex maxPendingSessions="2147483647"
maxPendingMessagesPerSession="2147483647"
inactivityTimeout="02:00:00"
serverPollTimeout="00:05:00"/>
<httpTransport />
</binding>
</customBinding>
</bindings>


Step III
Registering the pollingduplex extention
In order to use the polling duplex extension, we need to register it's DLL "System.ServiceModel.PollingDuplex.dll". To do so an extension for the DLL must be added. Here's the XML for the extension that is to be added just inside the <system.serviceModel> tag:
<extensions>
<bindingElementExtensions>
<add name="pollingDuplex"
type="System.ServiceModel.Configuration.PollingDuplexElement,
System.ServiceModel.PollingDuplex" />
</bindingElementExtensions>
</extensions>


Now here's how all the XML looks like:
<?xml version="1.0"?>
<!--
 For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
 -->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>

<system.serviceModel>
<extensions>
<bindingElementExtensions>
<add name="pollingDuplex"

type="System.ServiceModel.Configuration.PollingDuplexElement,
System.ServiceModel.PollingDuplex" />
</bindingElementExtensions>
</extensions>
<behaviors>
<serviceBehaviors>
<behavior name="BehaviourOfService">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="pollingDuplexBinding">
<binaryMessageEncoding />
<pollingDuplex
maxPendingSessions="2147483647"
maxPendingMessagesPerSession="2147483647"
inactivityTimeout="02:00:00" serverPollTimeout="00:05:00"/>
<httpTransport />
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>


Step IV
Endpoint of the Service
The next and final step is to create the end points for the service. Copy the following code to after the </bindings> line #40:
<services>
<service behaviorConfiguration="BehaviourOfService" name="MyPolling.Web.MyPollingService">
<endpoint address="" binding="customBinding" bindingConfiguration="pollingDuplexBinding"
contract="MyPolling.Web.IMyPollingService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>


The two important things that must be looked after is the name of the service and the contract for the endpoint. The name of the service is basically the location of my class MyPollingService, that is inside the MyPolling.Web namespace. And the contract of the endpoint is basically the location of the interface IMyPollingService, that is again inside MyPolling.Web.

Okay, the hard time is over, now I must go and get another cup of Coffee, meanwhile you build your solution.

My solution built with no error. If your solution does compile with errors, it's not my fault.

It's time now to consume the service at the client. At the client Silverlight project, right-click on the reference and choose "Add Service Reference". Click on the "Discover" button in the dialog, and you should see "MyPollingService" as shown in the figure below.

Name the namespace PollingService. In the end, try to remember the click event that we'd made in the mainpage at the beginning. Yes! your right, we need to write some code to consume the response from the server in that event.

    We need to create the endpoint URL for our service.
    Create a PollingDuplexHttpBinding for the service.
    Set the client so as to listen to the server's broadcast.

The following code will do it all, just add it in the button click event:
private void Start_OnClick(object sender, RoutedEventArgs e)
{
EndpointAddress URL = new EndpointAddress("http://localhost:" +
HtmlPage.Document.DocumentUri.Port + "/MyPollingService.svc");
PollingDuplexHttpBinding Bind = new PollingDuplexHttpBinding();
_client = new MyPollingServiceClient(Bind, URL);
TxtBlkInfo.Text = "Sent...";
_client.SubmitResultAsync("Hello Server");

_client.ReturnResultReceived +=

new EventHandler<ReturnResultReceivedEventArgs>(_client_ReturnResultReceived);

}


In the end at line #9 I've created an event handler for the event when the server broadcasts the request. We need to continuously update the value of the Text Block with the results the server sends. So in the handler just add the following line:
void _client_ReturnResultReceived(object sender, ReturnResultReceivedEventArgs e)
{

TxtBlkInfo.Text = e.rS;


A long journey has come to an end. Just press "F5", my darling key, and hope your project compiles and runs successfully. Fingers crossed

Mine did. And yes on pressing the "send message" button the text block's value is updating continuously.



Silvelight Hosting - HostForLIFE :: Silverlight Grid Layout Control Example

clock October 1, 2021 08:13 by author Peter

In this article we will be seeing how to create Silverlight Grid Layout using Visual studio 2010. The term layout describes the process of sizing and positioning objects in your Silverlight-based application. In Silverlight we have 3 layout elements namely Canvas, StackPanel and Grid. In this we will be seeing how to create Grid layout in Silverlight.

StackPanel:
It defines a grid area which consists of rows and columns. By default it contains one row and one column. It is the root element used by the Visual Studio Silverlight template. It enables you to o create a variety of object layouts. You can position child controls in specific cells of the Grid by using the Grid.Column and Grid.Row.

Grid.Row:
It is used to place the child controls in the particular row of the grid.

Grid.Column:
It is used to place the child controls in the particular column of the grid.

ShowGridLines-True:
If you set ShowGridLines to true gridlines will be shown.


ShowGridLines-False:

Steps Involved:
Creating a Silverlight Application:

  • Open Visual Studio 2010.
  • Go to File => New => Project.
  • Select Silverlight from the Installed templates and choose the Silverlight Application template.
  • Enter the Name and choose the location.
  • Click OK.
  • In the New Silverlight Application wizard check the "Host the Silverlight Application in a new Web site".
  • Click OK.

Creating the Grid Layout:
I. Open MainPage.xaml file and replace the code with the following.
<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="layoutRoot" ShowGridLines="True"  Height="200" Width="400" Background="Orange">
        <Grid.RowDefinitions>
            <RowDefinition Height="32*" />
            <RowDefinition Height="121*" />          
        </Grid.RowDefinitions>
        <TextBlock Text="PROFILE" FontFamily="Verdana" FontSize="14" FontWeight="Bold" Foreground="White" Margin="14,20,-14,99"
Grid.RowSpan="2"></TextBlock>       
        <Grid Grid.Row="1" ShowGridLines="True" Background="White">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="144*" />
                <ColumnDefinition Width="256*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="50*" />
                <RowDefinition Height="50*" />
                <RowDefinition Height="50*" />
                <RowDefinition Height="50*" />
                <RowDefinition Height="50*" />
            </Grid.RowDefinitions>
            <TextBlock Text="Name :" FontFamily="Verdana" Grid.Row="1" Grid.Column="0"  FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2" ></TextBlock>
            <TextBlock Text="About Me :" FontFamily="Verdana" Grid.Row="2" Grid.Column="0" FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2" ></TextBlock>
            <TextBlock Text="Country :" FontFamily="Verdana" Grid.Row="3" Grid.Column="0" FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2" ></TextBlock>          
            <TextBlock Text="Vijai Anand.R" FontFamily="Verdana" Grid.Row="1" Grid.Column="1" FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2"></TextBlock>
            <TextBlock Text="SharePoint Developer" FontFamily="Verdana" Grid.Row="2" Grid.Column="1" FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2"></TextBlock>
            <TextBlock Text="India" FontFamily="Verdana" Grid.Row="3" Grid.Column="1" FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2"></TextBlock>       
        </Grid>      
    </Grid>     
</UserControl>

ii. Build the solution.

iii. Hit ctrl+F5.



Silvelight 6 Hosting - HostForLIFE :: Difference Between WPF and Silverlight and Advantages of WPF

clock September 3, 2021 08:41 by author Peter

Many times in interview one question commanly used that is Difference Between WPF and Silverlight and Advantages of WPF, so by considering above requirement i have decided to write this blog to help freshers and job seekers also who might be wants to know about it.


So let us see

Difference Between  WPF And SilverLight:

  • WPF is based off of the desktop CLR which is the full version of the CLR.
  • Silverlight is based on a much smaller and more compact CLR which provides a great experience but does not have the full breadth
  • of CLR features. It also has a much smaller version of the BCL
  • WPF you can create Windows App, Navigation app and XBAP (IE based) applicationWith Silverlight you can create only XAP (Browser based application.).
  • WPF supports 3 types of routed events (direct, bubbling, and tunneling). Silverlight supports direct and bubbling only.
  • Silveright does not support MultiBinding.
  • Silverlight supports the XmlDataProvider but not the ObjectDataProvider. WPF supports both.

Advantage of WPF:
Broad Integration: Prior to WPF, it was very difficult to use 3D, Video, Speech, and rich document viewing in addition to normal 2D Graphics and controls would have to learn several independent technologies. WPF covers all these with consisting programming model as well as tight integration when each type of media gets composited and rendered.

Resolution Independence: WPF applications are device independent i.e., smart client applications. Like normal applications it dont get decrease the size as the resolution gets increase. This is possible because WPF emphasis on vector graphics.

Hardware Acceleration: WPF is built on top of Direct 3D, content in a WPF application whether 2D or 3D, Graphics or text is converted to 3D triangles, textures and other Direct 3D objects and then rendered by hardware. WPF applications can get the benefit of hardware acceleration for smoother graphics and all round better performance.

Declerative Programming: WPF takes the declarative programming to the next level with the introduction of Extensible Application Markup Language(XAML)

XAML is like HTML in web used for creating the interface, resulting graphical designers are empowered to contribute directly to the look and feel of applications.



Silvelight 6 Hosting - HostForLIFE.eu :: Rectangle in Silverlight

clock June 17, 2021 08:29 by author Peter

Silverlight Rectangle Control
This article demonstrates how to create and use a Rectangle control in Silverlight using XAML and C#.


The Rectangle object represents a rectangle shape and draws a rectangle with the given height and width. The Width and Height properties of the Rectangle class represent the width and height of a rectangle. The Fill property fills the interior of a rectangle. The Stroke property sets the color and StrokeThickness represents the width of the outer line of a rectangle.

Creating a Rectangle

The Rectangle element represents a Silverlight Rectangle control in XAML.
<Rectangle/>

The code snippet in Listing 1 creates a rectangle by setting its width and height properties to 200 and 100 respectively. The code also sets the black stroke of width 4.
<Rectangle
    Width="200"
    Height="100"
    Fill="Blue"
    Stroke="Black"
    StrokeThickness="4" />


The output

The CreateARectangle method listed in Listing 2 draws same rectangle in Figure 1 dynamically.
/// <summary>
/// Creates a blue rectangle with black border
/// </summary>
public void CreateARectangle()

{
    // Create a Rectangle
    Rectangle blueRectangle = new Rectangle();
    blueRectangle.Height = 100;
    blueRectangle.Width = 200;           

    // Create a blue and a black Brush
    SolidColorBrush blueBrush = new SolidColorBrush();
    blueBrush.Color = Colors.Blue;
    SolidColorBrush blackBrush = new SolidColorBrush();
    blackBrush.Color = Colors.Black;

     // Set Rectangle's width and color
    blueRectangle.StrokeThickness = 4;
    blueRectangle.Stroke = blackBrush;

    // Fill rectangle with blue color
    blueRectangle.Fill = blueBrush;

    // Add Rectangle to the Grid.

    LayoutRoot.Children.Add(blueRectangle);

}


The RadiusX and RadiusY properties set the x-axis and y-axis radii of the ellipse that is used to round the corner of a rectangle.  By adding the following lines of code to Listing 7 creates a rounded rectangle, which looks like Figure 2.
// Set roundness

blueRectangle.RadiusX = 20;
blueRectangle.RadiusY = 20;

Formatting a Rectangle
We can use the Fill property of the Rectangle to draw a rectangle with any kind of brush including a solid brush, linear gradient brush, radial gradient brush, or an image brush. The code in Listing 3 uses linear gradient brushes to draw the background and foreground of a Rectangle.
<Rectangle
    Width="200"
    Height="100"          
    Stroke="Black"
    StrokeThickness="4" >

    <Rectangle.Fill>
        <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >
            <GradientStop Color="Blue" Offset="0.1" />
            <GradientStop Color="Orange" Offset="0.25" />
            <GradientStop Color="Green" Offset="0.75" />
            <GradientStop Color="Red" Offset="1.0" />
        </LinearGradientBrush>
    </Rectangle.Fill>
</Rectangle>


The new Rectangle looks like Figure 3.

Setting Image as Background of a Rectangle
To set an image as background of a Rectangle, we can set an image brush as the Fill of the Rectangle. The code in Listing 4 sets fills the rectangle with an image.   
<Rectangle.Fill >
    <ImageBrush ImageSource="dock.jpg" />
</Rectangle.Fill >


The new output looks like

Drawing a Semi-transparent Rectangle
The Opacity property represents the transparency of a Rectangle. The value of Opacity is between 0 and 1, where 0 is fully transparent and 1 is fully opaque. The code listed in Listing 5 generates a semi-transparent shape.
<Rectangle
    Width="200"
    Height="100"          
    Stroke="Black"
    StrokeThickness="4"
    Opacity="0.5">


The new output looks like

In this article, I discussed how we can create a Rectangle control in Silverlight at design-time using XAML and at run-time using C#.  We also saw how we can format a Rectangle by setting its fill property. After that, we saw you to set an image as the background of a Rectangle. In the end, we saw how to draw a semi-transparent rectangle.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in