European Silverlight 4 & Silverlight 5 Hosting BLOG

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

European Silverlight 6 Hosting - Nederland :: Silverlight 5 Viewbox Control

clock March 15, 2019 09:45 by author Peter

This article will explore how to use the ViewBox control in Silverlight 6. The ViewBox control allows you to place a child control such as Image within it in such a way that it will be scaled appropriately to fit the available without any distortion. It is typically used in 2D graphics.

We will begin with creating a new Silverlight 6 project. Modify the existing XAML code of MainPage.xaml so that a Grid of 1 column and three rows is created. The code for the same is shown below:

<UserControl x:Class="SilverlightDemo.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" xmlns:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/ sdk HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
    </Grid>
</UserControl>

Drag and drop the Viewbox control from the Toolbox into the XAML code between the <Grid></Grid> tags. Specify its row and column in the grid to be 0. The resulting code is seen below.

<UserControl x:Class="SilverlightDemo.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" xmlns:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/ sdk HorizontalAlignment="Stretch" VerticalAlignment="Stretch">        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
         <controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
  </controls:Viewbox
    </Grid>
</UserControl>

Drag and drop the Viewbox control from the Toolbox into the XAML code between the <Grid></Grid> tags. Specify its row and column in the grid to be 0. The resulting code is seen below.

<UserControl x:Class="SilverlightDemo.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" xmlns:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/ sdk HorizontalAlignment="Stretch" VerticalAlignment="Stretch">        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
         <controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
  </controls:Viewbox
    </Grid>
</UserControl>

Right click on the project name in the Solution Explorer pane and select Add Existing Item option. Choose the image "Winter.jg" from the My Documents\My Pictures\Sample Pictures folder.

Drag and drop an Image control in between the <controls:ViewBox> and </controls:ViewBox> tag and modify its code as shown below, to specify its source and size.

    <Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
         <controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
            <Image Source="Winter.jpg" Height="40" Width="40"></Image>
        </controls:Viewbox>
    </Grid>

Drag and drop another ViewBox and then an Image control in between the second <controls:ViewBox> and </controls:ViewBox> tag.

Modify the XAML as shown below:

    <Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
         <controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
            <Image Source="Winter.jpg" Height="40" Width="40"></Image>
        </controls:Viewbox>
<controls:Viewbox Grid.Row="1" Grid.Column="0" Height="70" Width="90">
    <Image Source="Winter.jpg" Height="40" Width="40"></Image></controls:Viewbox
    </Grid>

Save the solution, build and execute it. When you see the output, you will observe that the two images show no distortion whatsoever though their height and width are not the same. This has happened because of the ViewBox.

HostForLIFE.eu Silverlight 6 Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European Silverlight 6 Hosting - HostForLIFE.eu :: Tic Tac Toe, Silverlight Drawing Basics

clock August 16, 2018 11:32 by author Peter

Silverlight is being on high recognition in the industry and it is really cool! In this article I am trying to create a marker control that allows the user to mark certain areas on the image canvas.  This will work as the drawing board for our Tic Tac Toe game.  We can see the usage of Canvas and its Children property applied with the Line class.

The application provides with a layer of buttons on choosing the pen, eraser or the color selector.  The board is represented by a Canvas class.

Canvas
In this application, the Canvas instance serves as our main drawing board.  The canvas is named BoardCanvas.  The drawings over the canvas are captured as Line objects and added to the Children property of the canvas.  The Children property accepts of type UIElement.

Line
The Line instances are used whenever the user marks over the board.  For each stroke a number of line objects are created to represent the stroke.  The user can choose two colors from the screen.
Repeating  that the line objects are created and added to the Children property of the canvas.

Delete
The delete functionality allows the user to delete the line under mouse cursor position.  This helps the user to remove an unwanted line.

The functionality is implemented by taking the mouse X, Y position and parsing through the line collection.  Each line's X, Y will be checked with the mouse positions and if a match found, the line is deleted from the canvas object.

Clear
There is a Clear button on the screen that will clear the board canvas. This will quickly help the user to restart the game.

The functionality is implemented by clearing all the lines from the canvas Children property.

Functionality Explained

The enumeration Mode is used to represent the active drawing mode of the application.  When the application starts, the default mode will be Draw.
public enum Mode
{
    None,
    Draw,
    Delete
}

When the user presses the Pen button, the mode will be set to Draw.

private void PenButton_Click(object sender, RoutedEventArgs e)
{
    _mode = Mode.Draw;
}


When the user presses the Delete button, the mode will be set to Delete.
private void Delete_Click(object sender, RoutedEventArgs e)
{
    _mode = Mode.Erase;
}

When the user presses, the Clear button, there is no mode change – the ClearAll() method is called.  The ClearAll() method will clear the Children property of the canvas and resets the mode to Draw. There is a private variable _lines which is used to hold all the lines of the drawing.
private void ClearAll()
{
    foreach (Line line in _lines)
        BoardCanvas.Children.Remove(line);
    _lines.Clear();
    _mode = Mode.Draw;
}



European Silverlight 6 Hosting - HostForLIFE.eu :: Creating a Beautiful Splash Screen For Silverlight Applications

clock July 26, 2018 08:18 by author Peter

There are many other great articles and blog posts on how to create simple Silverlight Splash Screens. This article adds on top of them and helps you design a more complex splash screen with Story Boards and Floating Text Blocks. I am not a great designer and thus I am taking a design que from Telerik's Silverlight Demos splash screen. They have some amazing designers and their splash screen is an amazing example of that. If you have not already noticed it please visit http://demos.telerik.com/silverlight/ and have a look yourself. We will try to replicate the same behavior in our splash screen. Here is a step-by-step guide to do this.

1. Create your XAML
In order to add the splash screen you will first need to add a new Silverlight 1.0 JavaScript (we will refer to it as SLJS for the sake of writing simplicity) page on your server side code.

Since you cannot modify this file in Blend, I created a new Silverlight project and created a new Silverlight User control in it.
Once I had completed the design of this page in Blend, I copied the content to the Silverlight JS page on the server side.
I had to make a few modifications that are listed below.

  • First delete the x:class namespace as that is not supported on a SLJS page
  • Also delete the underlying code file (in my case it was SplashScreen.xaml.cs)
  • I added a storyboard animation to float the text from left to right

<Grid.Resources>
  <Storyboardx:Name="sb1"RepeatBehavior="1x"Completed="onCompleted">
    <DoubleAnimationDuration="0:0:5"To="255"
    Storyboard.TargetProperty="X"Storyboard.TargetName="myTranslate"d:IsOptimized="True"/>
  </Storyboard>
</Grid.Resources>

 
Based on your design, the following content may change (I designed it to match the same as Telerik's splash page):
<Grid Background="#FFF4F4F4" RenderTransformOrigin="0.5,0.5"> <Grid.RowDefinitions> <RowDefinition Height="120"/> <RowDefinition Height="32"/> <RowDefinition Height="8"/> <RowDefinition Height="20"/>
 <RowDefinition Height="375*"/> </Grid.RowDefinitions> <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Grid.Row="0" Text="Silverlight" VerticalAlignment="Top" Height="153" Width="806" FontSize="133.333"
Foreground="#FFEEEEEE" Grid.RowSpan="3"/> <!--<StackPanel Orientation="Horizontal" Grid.Row="1" Margin="100,0,0,0" >
<Image Source="/Content/np_logo.PNG" Margin="0,0,5,0" Width="32" />
<TextBlock Text="Netpractise" FontSize="26.667" Foreground="Black"  FontFamily="Moire Light" x:Name="editing" FontWeight="ExtraBold" Height="32"/>
</StackPanel>--> <Image Source="/Content/np.PNG" Grid.Row="1" Margin="100,0,0,0" HorizontalAlignment="Left" /> <Rectangle Height="5" Fill="#FFA0DA0A" Width="200" HorizontalAlignment="Left"  Margin="100,0,0,0"
Grid.Row="2"/> <!--<TextBlock Text="digital communication innovation" Loaded="onTextBoxDigitalLoaded" Margin="100,0,0,0"  HorizontalAlignment="Left" FontFamily="Moire" FontSize="13.333" Height="16" Grid.Row="3"/>-->
<Image Source="/Content/baseline.PNG"  Margin="100,0,0,0" Width="300"  HorizontalAlignment="Left" Grid.Row="3"/> <!-- Progress bar--> <Rectangle Fill="#FF24A9F3" Height="5" HorizontalAlignment="Left" x:Name="uxProgress"
Grid.Row="2"/> <!--floating text boxes--> <TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="Be it Videos, Images, Flash or Audio we support all."
VerticalAlignment="Center" Grid.Row="4" Height="400"
Width="510" Foreground="#FF24A9F3" FontSize="48" FontFamily="Segoe WP Light" RenderTransformOrigin="0.5,0.5"
Loaded="onTextBoxLoaded" Margin="20,0,0,0"> <TextBlock.RenderTransform> <TransformGroup> <TranslateTransform x:Name="myTranslate"/> </TransformGroup> </TextBlock.RenderTransform> <!--The story board can be placed
within this to run from XAML or JS functions can be used.--> <!--<TextBlock.Triggers>
<EventTrigger RoutedEvent="TextBlock.Loaded">
<BeginStoryboard>
</BeginStoryboard>
</EventTrigger>               
</TextBlock.Triggers>--> </TextBlock> <TextBlock x:Name="txtProgressPercentage" Grid.Row="4" HorizontalAlignment="Right" Margin="0,-150,-170,0" VerticalAlignment="Center" TextWrapping="Wrap" Height="358" Width="651"
FontSize="300" Foreground="#FFE4E4E4"/> </Grid>


2. Code the logic in JavaScript file
When you add a new SLJS page in your application, it also creates an underlying .js file where you can write your code logic.
All I had to do was to create 3 functions in it ; they are:

onSourceDownloadProgressChanged

This is to update the progress bar and the big textblock that shows % update in numbers.
var i = 0;
function onSourceDownloadProgressChanged(sender, eventArgs)
{
sender.findName("txtProgressPercentage").Text = Math.round(Math.round((eventArgs.progress * 1000)) / 10, 1).toString();
//get browser width   var width = window.document.body.clientWidth;
sender.findName("uxProgress").Width = (width * eventArgs.progress);
}
 

onTextBoxLoaded
This is to trigger the first story board.
function onTextBoxLoaded(sender, eventArgs)
{
// Retrieve the Storyboard and begin it.     sender.findName("sb1").begin();
}


onCompleted
This is to change the Text of the floating Text box and start the Storyboard again with updated text.
function onCompleted(sender, eventArgs)
{
try{
i++;
sender.findName("myTranslate").X = 0;
switch (i) {
case 1:
sender.findName("textBlock").Text = "This is my first content";
break;
case 2:
sender.findName("textBlock").Text = "This is my second content";
break;
case 3:
sender.findName("textBlock").Text = "This is my third content.";
break;
case 4:
sender.findName("textBlock").Text = "This is my fourth content";
break;
case 5:
sender.findName("textBlock").Text = "This is my fifth content.";
break;
case 6:
sender.findName("textBlock").Text = "This is my sixth content";
i = 1;
break;
}
}catch(e){
}
sender.findName("sb1").begin();


I have 6 text block contents that show up on the screen one by one. You can have as many as you want and can also pull them from a collection if that's what you need.

3. Updating the Default.html or Default.aspx page
This is an important and the last step to hook the splash screen we created to our Silverlight application.
Just add a few parameters and a link to the JavaScript file just below the </head> tag.
<script type="text/javascript" src="splashscreen.js"></script>

The following new parameters go in <div id="silverlightControlHost">:
<param name="splashscreensource" value="SplashScreen.xaml" /> <param name="onSourceDownloadProgressChanged" value="onSourceDownloadProgressChanged" />

The first parameter just tells your app which splash screen to load at startup and the second one calls the js function that eventually updates the progress bar and % progress textblock with numbers.



European Silverlight 6 Hosting - HostForLIFE.eu :: Update Data Using Silverlight RIA Enabled ServiceToday

clock July 10, 2018 11:28 by author Peter

Update Data Using Silverlight RIA Enabled ServiceToday, in this article let's play around with one of the interesting and most useful concepts in Silverlight.

Question: What is update data using Silverlight RIA enabled service?
In simple terms "This application enables to update the data in the database with help of Silverlight RIA enabled service. It uses base platform of entity framework to communicate with database".

Step 1: Create a database named "Company" with employee table in it.

Step 2: Open up Visual Studio and create a new Silverlight application enabled with RIA Services
Step 3: When the project is created. Right-click on RIA Service project and add new entity data model framework and set it up for previously created database.
Step 4: Again right click on RIA service project and add Domain Service Class as new item.
Step 5: Complete code of EmployeeDomain.cs looks like this (Domain Service Class)
namespace SilverlightRIAInsert.Web
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.ServiceModel.DomainServices.EntityFramework;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
// Implements application logic using the CompanyEntities context.
// TODO: Add your application logic to these methods or in additional methods.
// TODO: Wire up authentication (Windows/ASP.NET Forms) and uncomment the following to disable anonymous access
// Also consider adding roles to restrict access as appropriate.
// [RequiresAuthentication][EnableClientAccess()]
public class EmployeeDomain : LinqToEntitiesDomainService<CompanyEntities>
{
    // TODO:// Consider constraining the results of your query method.  If you need additional input you can
    // add parameters to this method or create additional query methods with different names.
    // To support paging you will need to add ordering to the 'Employee'
    query.public IQueryable<Employee> GetEmployee()
    {
        return this.ObjectContext.Employee;
    }
    public void InsertEmployee(Employee employee)
    {
        if ((employee.EntityState != EntityState.Detached))
        {
            this.ObjectContext.ObjectStateManager.ChangeObjectState(employee, EntityState.Added);
        }
        else{this.ObjectContext.Employee.AddObject(employee);
        }
    }
    public void UpdateEmployee(Employee currentEmployee)
    {
        this.ObjectContext.Employee.AttachAsModified(currentEmployee, this.ChangeSet.GetOriginal(currentEmployee));
    }
    public void DeleteEmployee(Employee employee)
    {
        if ((employee.EntityState != EntityState.Detached))
        {
            this.ObjectContext.ObjectStateManager.ChangeObjectState(employee, EntityState.Deleted);
        }
        else{this.ObjectContext.Employee.Attach(employee);
           this.ObjectContext.Employee.DeleteObject(employee);
        }
    }
}
}


Step 6: Now rebuild the solution file.
Step 7: The complete code of MainPage.xaml looks like this:
<usercontrolx:class="SilverlightRIAInsert.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="543">
<Gridx:Name="LayoutRoot"Width="608">
<TextBlockHeight="23"HorizontalAlignment="Left"Margin="152,29,0,0"Name="textBlock1"Text="Id"FontFamily="Verdana"FontSize="15"VerticalAlignment="Top"/>
<TextBoxHeight="23"HorizontalAlignment="Left"Margin="252,25,0,0"Name="textBox1"VerticalAlignment="Top"Width="120"/>
<TextBlockHeight="23"HorizontalAlignment="Left"Margin="150,72,0,0"Name="textBlock2"Text="FirstName"FontFamily="Verdana"FontSize="15"VerticalAlignment="Top"/>
<TextBoxHeight="23"HorizontalAlignment="Left"Margin="252,68,0,0"Name="textBox2"VerticalAlignment="Top"Width="120"/>
<TextBlockHeight="23"HorizontalAlignment="Left"Margin="150,113,0,0"Name="textBlock3"Text="LastName"FontFamily="Verdana"FontSize="15"VerticalAlignment="Top"/>
<TextBoxHeight="23"HorizontalAlignment="Left"Margin="252,113,0,0"Name="textBox3"VerticalAlignment="Top"Width="120"/>
<ButtonContent="Update"FontFamily="Verdana"FontSize="19"Background="DeepSkyBlue"Height="44"HorizontalAlignment="Left"Margin="252,206,0,0"Name="button1"VerticalAlignment="Top"Width="120"Click="button1_Click"/>
<TextBoxHeight="23"HorizontalAlignment="Left"Margin="252,155,0,0"Name="textBox4"VerticalAlignment="Top"Width="120"/>
<TextBlockHeight="23"HorizontalAlignment="Left"Margin="152,155,0,0"Name="textBlock4"Text="Age"FontFamily="Verdana"FontSize="16"VerticalAlignment="Top"/>
</Grid>"
</usercontrol>


Step 8: The complete code of MainPage.xaml.cs looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.DomainServices.Client;
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;
using SilverlightRIAUpdate.Web;
namespace SilverlightRIAUpdate
{
public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
    }
    EmployeeDomain objDomain = new EmployeeDomain();
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        EntityQuery<Employee> query = objDomain.GetEmployeeQuery();
        objDomain.Load(query, UpdateLoad, null);
        MessageBox.Show("Data Updated Successfully");
    }
    public void UpdateLoad(LoadOperation<Employee> emp)
    {
        foreach (Employee e in objDomain.Employees)
        {
            if (e.Id == int.Parse(textBox1.Text))
           {
                e.FirstName = textBox2.Text;
                e.LastName = textBox3.Text;
                e.Age = int.Parse(textBox4.Text);
                objDomain.SubmitChanges();
                break;
            }
        }
    }
}
}

 



Silverlight 6 Hosting - HostForLIFE.eu :: How to Create Pop Up Notifications

clock October 15, 2015 17:11 by author Rebecca

In this post, I will tell you how to create pop up notification in Silverlight. I will separate the kinds of notification into: Alert, Prompt and Confirm popup box.

There is a class called System.Windows.Browsers that comes with Silverlight. Also, there are lots of methods to create alert, prompt and confirm box using JavaScript. Let’s look further into each notification one by one:

1. Alert

HtmlPage.Window.Alert("Alert from Silverlight screen");

Same thing can be achieved using the Silverlight MessageBox. The only difference is that in case of MessageBox, you don't have the alert symbol. But at the same time with MessageBox you have the option to display appropriate title for the pop up.

MessageBox.Show("MessageBox for Silverlight", "AlertMessageBox", MessageBoxButton.OK)

2. Confirm

HtmlPage.Window.Confirm("Do you know how to call Alert from Silverlight");

The confirm method returns bool value, this can be used to perfrom further action depending upon if user clicks OK or Cancel button. Below code display how to handle the same.

bool isConfirmed = HtmlPage.Window.Confirm("Do you know how to call Alert from Silverlight");

if (isConfirmed)

 {

   //Perform some action;

 }
This thing can also be achieved using the Silverlight MessageBox. The only difference is that in case of MessageBox return type is not bool but Enum of type MessageBoxResult. Also the 3rd parameter which is of enum type MessageBoxButton should be MessageBoxButton.OkCancel

MessageBox.Show("MessageBox for Silverlight", "AlertMessageBox", MessageBoxButton.OKCancel);

MessageBoxResult isConfirmed = MessageBox.Show("MessageBox for Silverlight", "Alert MessageBox", MessageBoxButton.OKCancel);

if (isConfirmed == MessageBoxResult.OK)

 {

   //Perfrom some Action;

 }

3. Prompt

HtmlPage.Window.Prompt("whatis name of site?");

Prompt method returns string method. The input provided can be used to perform further action

string inputValue = HtmlPage.Window.Prompt("what is name of site?");

if (inputValue.Trim() == "Experts Comment")

 {

   //Perfrom some action;

 }


HostForLIFE.eu Silverlight 6 Hosting

HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Silverlight 6 Hosting - HostForLIFE.eu :: How to Create a Similar List like Mac using Silverlight

clock October 8, 2015 13:09 by author Rebecca

In this tutorial, we will create the standard Silverlight ListBox will be customized to be functionally similar to a ListBox you would find on a Mac.

The XAML for this tutorial contains a custom style that we use to disable the scrollbar:

<UserControl x:Class="CustomListBox.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.Resources>
            <Style x:Key="ListBoxStyle1" TargetType="ListBox">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBox">
                            <Grid x:Name="LayoutRoot">
                                <Border Padding="5" BorderBrush="#000000" BorderThickness="1" Background="#ffffff" CornerRadius="0">
                                    <ScrollViewer x:Name="ScrollViewer" VerticalScrollBarVisibility="Hidden" Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="0">
                                        <ItemsPresenter />
                                    </ScrollViewer>
                                </Border>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Grid.Resources>
        <StackPanel Margin="4" HorizontalAlignment="Left">
            <RepeatButton Width="200" Height="22" Click="Up_Click">
                <Polygon Points="5,0 10,10 0,10 5,0" Fill="#222222" />
            </RepeatButton>
            <ListBox x:Name="listbox" Width="200" Height="150" Style="{StaticResource ListBoxStyle1}">
                <ListBoxItem Content="Item 1" />
                <ListBoxItem Content="Item 2" />
                <ListBoxItem Content="Item 3" />
                <ListBoxItem Content="Item 4" />
                <ListBoxItem Content="Item 5" />
                <ListBoxItem Content="Item 6" />
                <ListBoxItem Content="Item 7" />
                <ListBoxItem Content="Item 8" />
                <ListBoxItem Content="Item 9" />
                <ListBoxItem Content="Item 10" />
                <ListBoxItem Content="Item 11" />
                <ListBoxItem Content="Item 12" />
            </ListBox>
            <RepeatButton Width="200" Height="22" Click="Down_Click">
                <Polygon Points="5,10 10,0 0,0 5,10" Fill="#222222" />
            </RepeatButton>
        </StackPanel>
    </Grid>
</UserControl>

In XAML, just apply the custom style and populate it with some test data.  There are also two repeat buttons, an up and down that will handle the scrolling for us:

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 CustomListBox
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }

        private void Up_Click(object sender, RoutedEventArgs e)
        {
            if (listbox.Items.Count > 0)
            {
                int newIndex = listbox.SelectedIndex - 1;

                if (newIndex < 0)
                {
                    newIndex = 0;
                }
                listbox.SelectedIndex = newIndex;
            }
        }

        private void Down_Click(object sender, RoutedEventArgs e)
        {
            if (listbox.Items.Count > 1)
            {
                int newIndex = listbox.SelectedIndex + 1;

                if (newIndex >= listbox.Items.Count)
                {
                    newIndex = listbox.Items.Count - 1;
                }
                listbox.SelectedIndex = newIndex;
            }
        }
    }
}

And now we're done!

HostForLIFE.eu Silverlight 6 Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Silverlight 6 Hosting - HostForLIFE.eu :: How to Control Playback in A Video

clock September 17, 2015 11:07 by author Rebecca

Using videos in a Silverlight based application is a very exciting feature. In this article, we will learn how we can control the playback of movie using some coding in code-behind. Let's see how!

Dealing with Automatic Start

By default videos automaticall get started when we run the project, it is distracting feature from the users point of view. To change auto start false, select the video on stage and in properties uncheck the 'AutoPlay' option.

Dealing with Endless Playback

By default, when the video reaches the end then it stops and does not start again. To change such a setting follow the steps:

1. Select the video on stage

2. In Properties, switch the mode from 'Properties' to 'Events'.

3. In the Event list, point to 'MediaEnded' label and type the event handler name (I will be using md_ended_eve) and then press tab to apply it and it automatically switches you to code-behind with a new event.

4. Now type the following code inside event handler:

(intro_wmv).Stop();
(intro_wmv).Play();

In above code 'intro_wmv' is my media fine name.

5. Now test the application.

XAML Code
<Grid
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          x:Class="SilverlightApplication1.MainPage"
          Width="640" Height="480">
          <MediaElement x:Name="intro_wmv"
          Margin="54,64,104,60"
          Source="/intro.wmv"
          Stretch="Fill"
          MediaEnded="md_ended_eve" AutoPlay="False"/>
</Grid>

XAML.CS Code
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication1
{
       public partial class MainPage : Grid
       {
              public MainPage()
              {
                     // Required to initialize variables
                     InitializeComponent();
              }
              private void md_ended_eve(object sender, System.Windows.RoutedEventArgs e)
              {
                     // TODO: Add event handler implementation here.
                     (intro_wmv).Stop();
                     (intro_wmv).Play();
              }
       }
}

Control Video Playback by Pause and Play

By default in Silverlight video plays and we can't control it by pausing and playing. But by writing some lines in code-behind we can control this playback. For this we have to create the event as we saw in above example. Let's follow the steps:

1. Open the event explorer by switching the property (look above image).

2. Type the event name in 'MouseLeftButtonDown', I will be using here 'pause_start_evn' and press tab to switch in event handler mode.

3. In the appeared event type the following code:

private bool IsPaused=true;
private void pause_start_evn(object sender, System.Windows.Input.MouseButtonEventArgs e)
              {
                     // TODO: Add event handler implementation here.
                     if(IsPaused)
                     {
                           (intro_wmv as MediaElement).Play();
                           IsPaused=false;
                     }
                     else
                     {
                           (intro_wmv as MediaElement).Pause();
                           IsPaused=true;
                     }
   }

4. Now test the application and check by right mouse click on video surface.

XAML Code
<Grid
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          x:Class="SilverlightApplication1.MainPage"
          Width="640" Height="480">
          <MediaElement x:Name="intro_wmv"
          Margin="54,64,104,60"
          Source="/intro.wmv"
          Stretch="Fill"
          MediaEnded="md_ended_eve"
          MouseLeftButtonDown="pause_start_evn"/>
</Grid>

XAXM.CS Code

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication1
{
       public partial class MainPage : Grid
       {
              public MainPage()
              {
                     // Required to initialize variables
                     InitializeComponent();
              }

              private void md_ended_eve(object sender, System.Windows.RoutedEventArgs e)
              {
                     // TODO: Add event handler implementation here.
                     (intro_wmv).Stop();
                     (intro_wmv).Play();
              }
              private bool IsPaused=true;
              private void pause_start_evn(object sender, System.Windows.Input.MouseButtonEventArgs e)
              {
                     // TODO: Add event handler implementation here.
                     if(IsPaused)
                     {
                           (intro_wmv as MediaElement).Play();
                           IsPaused=false;
                     }
                     else
                     {
                           (intro_wmv as MediaElement).Pause();
                           IsPaused=true;
                     }
              }
       }
}

Now, that's all about the controlling of video playback in a Silverlight based application. Happy coding!

HostForLIFE.eu Silverlight 6 Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Silverlight 6 Hosting - HostForLIFE.eu :: How to Use ASP.NET to Create Silverlight Clock Apps

clock September 10, 2015 11:37 by author Rebecca

In this post, we will learn how to create Analog Clock completely from code behind using .NET Silverlight.

Step 1

Create a new project in Visual Studio and select "Silverlight Application".

Step 2

Open MainPage.xaml and add the following code:


    <UserControl x:Class="SilverlightAnalogClock.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"> 
            
        </Grid> 
    </UserControl> 

Step 3

Open MainPage.xaml.cs and add the following code:

    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.Media.Imaging; 
    using System.Windows.Shapes; 
     
    namespace SilverlightAnalogClock 
    { 
        public partial class MainPage : UserControl 
        { 
     
            public Canvas ClockArea = null; 
            public Rectangle secondHand = null; 
            public Rectangle minuteHand = null; 
            public Rectangle hourHand = null; 
     
            public RotateTransform secondHandRotate = null; 
            public RotateTransform minuteHandRotate = null; 
            public RotateTransform hourHandRotate = null; 
     
            public Ellipse outerCircle = null; 
     
            public Point centerPoint; 
            public double HEIGHT  = 0; 
            public double WIDTH  = 0; 
            public double RADIUS = 0; 
     
            public MainPage() 
            { 
                InitializeComponent(); 
     
                ClockArea = new Canvas() 
                { 
     
                    Width = 300, 
                    Height = 300, 
                    HorizontalAlignment = HorizontalAlignment.Left, 
                    VerticalAlignment = VerticalAlignment.Top 
     
                }; 
     
                ClockArea.SetValue(Grid.RowProperty, 0); 
                ClockArea.SetValue(Grid.ColumnProperty, 0); 
                ClockArea.Margin = new Thickness(0, 0, 0, 0); 
                this.LayoutRoot.Children.Add(ClockArea); 
     
                WIDTH = ClockArea.Width; 
                HEIGHT = ClockArea.Height; 
                centerPoint.X = (WIDTH/2); 
                centerPoint.Y = (HEIGHT/2); 
                      
                RADIUS = 400; 
                DrawClockFace(); 
     
                Point TOPPOINT = new Point(0, 0); 
     
                DrawMinuteHand(); 
                DrawSecondHand(); 
                DrawHourHand(); 
                DrawCenterCircle(); 
     
     
                //Start the Clock 
                ClockStart(); 
                 
     
            } 
     
            public void ClockStart() 
            { 
                // Create and Start the Thread Timer 
                System.Windows.Threading.DispatcherTimer clockTimer = new System.Windows.Threading.DispatcherTimer(); 
                clockTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000); 
                clockTimer.Tick += new EventHandler(Clock_Tick); 
                clockTimer.Start(); 
            } 
     
            // Get and Set the Angles of Each Hand at every Clock Ticks 
            public void Clock_Tick(object o, EventArgs sender) 
            { 
                double hourRotateValue = Convert.ToDouble(DateTime.Now.Hour.ToString()); 
                double minuteRotateValue = Convert.ToDouble(DateTime.Now.Minute.ToString()); 
                double secondRotateValue = Convert.ToDouble(DateTime.Now.Second.ToString()); 
                hourRotateValue = (hourRotateValue + minuteRotateValue / 60) * 30; 
                minuteRotateValue = (minuteRotateValue + secondRotateValue / 60) * 6; 
                secondRotateValue = Convert.ToDouble(DateTime.Now.Second.ToString()) * 6; 
                minuteHandRotate.Angle = minuteRotateValue; 
                hourHandRotate.Angle = hourRotateValue; 
                secondHandRotate.Angle = secondRotateValue; 
            } 
     
            // Draw Center Circle 
            public void DrawCenterCircle() 
            {             
                Ellipse centerCircle = new Ellipse() 
                { 
     
                    Width = 10, 
                    Height = 10, 
                    Stroke = new SolidColorBrush(Colors.Red), 
                    Fill = new SolidColorBrush(Colors.Red), 
                    HorizontalAlignment = HorizontalAlignment.Center, 
                    VerticalAlignment = VerticalAlignment.Center 
     
                }; 
     
                centerCircle.SetValue(Grid.RowProperty, 0); 
                centerCircle.SetValue(Grid.ColumnProperty, 0); 
                Canvas.SetLeft(centerCircle, (WIDTH / 2) - (centerCircle.Width / 2)); 
                Canvas.SetTop(centerCircle, (HEIGHT / 2) - (centerCircle.Height / 2)); 
                ClockArea.Children.Add(centerCircle); 
            } 
     
            // Draw Clock Face 
            public void DrawClockFace() 
            { 
                         
                int smallCircle = 5; 
     
                Color c = Colors.Blue; 
                int p = 0; 
     
                // Draw Shadow of Outer Circle 
                Ellipse outerCircleShadow = new Ellipse() 
                { 
                    Width = (WIDTH), 
                    Height = (WIDTH), 
                    Stroke = new SolidColorBrush(Colors.Gray), 
                    StrokeThickness = 5, 
                    HorizontalAlignment = HorizontalAlignment.Center, 
                    VerticalAlignment = VerticalAlignment.Center 
                     
                }; 
                
                outerCircleShadow.SetValue(Grid.RowProperty, 0); 
                outerCircleShadow.SetValue(Grid.ColumnProperty, 0); 
                Canvas.SetLeft(outerCircleShadow, (WIDTH / 2) - (outerCircleShadow.Width / 2) + 6.5); 
                Canvas.SetTop(outerCircleShadow, (HEIGHT / 2) - (outerCircleShadow.Height / 2) + 6.5); 
                ClockArea.Children.Add(outerCircleShadow); 
                
                //  Draw Outer Circle 
                outerCircle = new Ellipse() 
                { 
                    Width = (WIDTH ), 
                    Height = (WIDTH), 
                    Stroke = new SolidColorBrush(Colors.Black), 
                    StrokeThickness = 5, 
                    HorizontalAlignment = HorizontalAlignment.Center, 
                    VerticalAlignment = VerticalAlignment.Center 
                };             
                outerCircle.SetValue(Grid.RowProperty, 0); 
                outerCircle.SetValue(Grid.ColumnProperty, 0); 
                Canvas.SetLeft(outerCircle, (WIDTH / 2) - (outerCircle.Width / 2) + 4.5); 
                Canvas.SetTop(outerCircle, (HEIGHT / 2) - (outerCircle.Height / 2) + 4.5); 
                ClockArea.Children.Add(outerCircle); 
     
     
                outerCircle.Fill = new LinearGradientBrush() 
                    { 
                        EndPoint = new Point(1, 0), 
                        GradientStops = new GradientStopCollection() 
                        { 
                                new GradientStop() { Color = Colors.White, Offset = 0 }, 
                                new GradientStop() { Color = Colors.Gray, Offset = 0.5 }, 
                                 new GradientStop() { Color = Colors.White, Offset = 1 } 
                        } 
                    }; 
     
                int clockDigits = 3; 
                double rad = (WIDTH/2) - 10.0f; 
                // 60 Innner Dots as Small Circle 
                for (double i = 0.0; i < 360.0; i += 6)  
                {  
     
                double angle = i * System.Math.PI / 180; 
     
                int x = (int)(centerPoint.X + rad * System.Math.Cos(angle)); 
                int y = (int)(centerPoint.Y + rad * System.Math.Sin(angle)); 
     
                if (p % 5 == 0) 
                { 
                    smallCircle = 10; 
                    c = Colors.Orange;                 
                } 
                else 
                { 
                    smallCircle = 5; 
                    c = Colors.Blue; 
                } 
                if (p % 15 == 0) 
                { 
                    TextBlock tb = new TextBlock(); 
                    tb.Text = clockDigits.ToString(); 
                    tb.FontSize = 24; 
                     
                    tb.SetValue(Grid.RowProperty, 0); 
                    tb.SetValue(Grid.ColumnProperty, 0); 
                    Canvas.SetLeft(tb, x ); 
                    Canvas.SetTop(tb, y); 
                    if (clockDigits == 3) 
                    { 
                        Canvas.SetLeft(tb, x - 20); 
                        Canvas.SetTop(tb, y - 10); 
                    } 
                    if (clockDigits == 6) 
                    { 
                        Canvas.SetLeft(tb, x); 
                        Canvas.SetTop(tb, y - 30); 
                    } 
                    if (clockDigits == 9) 
                    { 
                        Canvas.SetLeft(tb, x + 15); 
                        Canvas.SetTop(tb, y - 10); 
                    } 
                    if (clockDigits == 12) 
                    { 
                        Canvas.SetLeft(tb, x - 10); 
                        Canvas.SetTop(tb, y + 5 ); 
                    }  
                   
                     
                    ClockArea.Children.Add(tb); 
                    clockDigits = clockDigits + 3; 
                } 
     
                p++; 
                
                            Ellipse innerPoints = new Ellipse() 
                            { 
                                Width = smallCircle, 
                                Height = smallCircle, 
                                Stroke = new SolidColorBrush(c), 
                                Fill = new SolidColorBrush(c), 
                                HorizontalAlignment = HorizontalAlignment.Center, 
                                VerticalAlignment = VerticalAlignment.Center 
                            }; 
                            innerPoints.SetValue(Grid.RowProperty, 0); 
                            innerPoints.SetValue(Grid.ColumnProperty, 0); 
                            Canvas.SetLeft(innerPoints, x); 
                            Canvas.SetTop(innerPoints, y); 
                            ClockArea.Children.Add(innerPoints); 
     
                } 
     
                 
            } 
            // Draw the Second Hand 
            public void DrawSecondHand() 
            { 
     
                double handLength = (HEIGHT / 2) - 20; 
                secondHand = new Rectangle() 
                { 
                    Width = 1, 
                    Height = handLength, 
                    Stroke = new SolidColorBrush(Colors.Red), 
                    Fill = new SolidColorBrush(Colors.Red), 
                    HorizontalAlignment = HorizontalAlignment.Center, 
                    VerticalAlignment = VerticalAlignment.Center 
                }; 
                 
                secondHand.SetValue(Grid.RowProperty, 0); 
                secondHand.SetValue(Grid.ColumnProperty, 0); 
                //Add Rotate Transformation 
                secondHandRotate = new RotateTransform(); 
                secondHandRotate.Angle = 0; 
                //Set Center for Rotation 
                secondHandRotate.CenterX = Canvas.GetLeft(secondHand); 
                secondHandRotate.CenterY = secondHand.Height; 
                secondHand.RenderTransform = secondHandRotate; 
                //Set Initial Position of Hand 
                Canvas.SetTop(secondHand, centerPoint.Y - handLength); 
                Canvas.SetLeft(secondHand, WIDTH/2);            
                ClockArea.Children.Add(secondHand); 
                
            } 
     
            public void DrawMinuteHand() 
            { 
                double handLength = (HEIGHT / 2) - 50; 
                minuteHand = new Rectangle() 
                { 
                    Width = 4, 
                    Height = handLength, 
                    Stroke = new SolidColorBrush(Colors.Black), 
                    Fill = new SolidColorBrush(Colors.Black), 
                    HorizontalAlignment = HorizontalAlignment.Center, 
                    VerticalAlignment = VerticalAlignment.Center 
                }; 
     
                minuteHand.SetValue(Grid.RowProperty, 0); 
                minuteHand.SetValue(Grid.ColumnProperty, 0); 
     
                minuteHandRotate = new RotateTransform(); 
                minuteHandRotate.Angle = 0; 
                minuteHandRotate.CenterX = Canvas.GetLeft(minuteHand); 
                minuteHandRotate.CenterY = minuteHand.Height; 
                minuteHand.RenderTransform = minuteHandRotate; 
                Canvas.SetTop(minuteHand, centerPoint.Y - handLength); 
                Canvas.SetLeft(minuteHand, WIDTH / 2); 
                ClockArea.Children.Add(minuteHand); 
     
            } 
            public void DrawHourHand() 
            { 
                double handLength = (HEIGHT / 2) - 80; 
                hourHand = new Rectangle() 
                { 
                    Width = 4, 
                    Height = handLength, 
                    Stroke = new SolidColorBrush(Colors.Black), 
                    Fill = new SolidColorBrush(Colors.Black), 
                    HorizontalAlignment = HorizontalAlignment.Center, 
                    VerticalAlignment = VerticalAlignment.Center 
                }; 
     
                hourHand.SetValue(Grid.RowProperty, 0); 
                hourHand.SetValue(Grid.ColumnProperty, 0); 
     
                hourHandRotate = new RotateTransform(); 
                hourHandRotate.Angle = 0; 
                hourHandRotate.CenterX = Canvas.GetLeft(hourHand); 
                hourHandRotate.CenterY = hourHand.Height; 
                hourHand.RenderTransform = hourHandRotate; 
                Canvas.SetTop(hourHand, centerPoint.Y - handLength); 
                Canvas.SetLeft(hourHand, WIDTH / 2);    
                ClockArea.Children.Add(hourHand); 
     
            } 
     
        } 
    } 


The Output

Now execute and you will get a fully drawn Silverlight Analog Clock.


HostForLIFE.eu Silverlight 6 Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Silverlight 6 Hosting UK - HostForLIFE.eu :: How to Use Silverlight Storyboard to Create Busy Indicator Bar

clock August 4, 2015 07:14 by author Rebecca

The Silverlight toolkit comes with Busy Indicator control, but some time you may need to develop custom Busy Indicator for your application. Here are the steps to create Busy Indicator using Silverlight StoryBoard.

Step 1: Create Silverlight Application

Create Silverlight application and add ProgressBar.xaml user control in your project.

Step 2: Code Progress Bar

Copy and paste below given code ten times and change grid name from circle0 through circle9. This code will be used to generate small filled circles.

<Grid x:Name="circle0" HorizontalAlignment="Center" Margin="0,0,0,0"
                    VerticalAlignment="Center" Opacity="0" RenderTransformOrigin="0.5,0.5">
     <Grid.RenderTransform>
          <TransformGroup>
            <ScaleTransform />
                  <SkewTransform />
                  <RotateTransform />
                  <TranslateTransform X="29" Y="-44" />
          </TransformGroup>
      </Grid.RenderTransform>
      <Ellipse HorizontalAlignment="Center" Margin="0,0,0,0" Width="10"
               RenderTransformOrigin="0.5,0.5" Stroke="{x:Null}" Height="10"
                        VerticalAlignment="Center">
          <Ellipse.Fill>
                   <RadialGradientBrush>
                   <GradientStop Color="#FF000000" />
                   <GradientStop Color="#00000000" Offset="1" />
                   <GradientStop Color="#7F000000" Offset="0.551" />
                   </RadialGradientBrush>
          </Ellipse.Fill>
          <Ellipse.RenderTransform>
                   <TransformGroup>
                   <ScaleTransform />
                   <SkewTransform />
                   <RotateTransform />
                   <TranslateTransform X="2" Y="2" />
                   </TransformGroup>
          </Ellipse.RenderTransform>
       </Ellipse>
       <Ellipse Height="9" HorizontalAlignment="Center" Margin="0,0,0,0"
            Width="9" RenderTransformOrigin="0.5,0.5"   VerticalAlignment="Center" Stroke="{x:Null}">
          <Ellipse.Fill>
                   <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                   <GradientStop Color="#FF9ED9E7" />
                   <GradientStop Color="#FF67BED9" Offset="1" />
                   </LinearGradientBrush>
          </Ellipse.Fill>
            <Ellipse.RenderTransform>
                  <TransformGroup>
                         <ScaleTransform />
                         <SkewTransform />
                         <RotateTransform />
                         <TranslateTransform X="0" Y="0" />
                  </TransformGroup>
            </Ellipse.RenderTransform>
          </Ellipse>
</Grid>

Step 3: Add  StoryBoard code

Add this StoryBoard in user control resources section. This will start Busy Indicator animation.

<Storyboard x:Name="StartAnimation">
            <DoubleAnimation Storyboard.TargetProperty="(UIElement.Opacity)"
                    Storyboard.TargetName="LayoutRoot" From="0" To="1" Duration="0:0:0.3">
            </DoubleAnimation>
</Storyboard>


Copy and paste below code ten times and change StoryBoard name from ProgressStoryboard0 through ProgressStoryboard9 and StoryBoard TargetName from circle0 through circle9 (you have already declared code for circles above). This code will be used to generate StoryBoard animation for Busy Indicator.

<Storyboard x:Name="ProgressStoryboard0">
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="circle0"
                    Storyboard.TargetProperty="(UIElement.Opacity)">
                <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0" />
                <SplineDoubleKeyFrame KeyTime="00:00:00.0050000" Value="1" />
                <SplineDoubleKeyFrame KeySpline="0,0,0.601999998092651,0.400999993085861"
                        KeyTime="00:00:00.7000000" Value="1" />
                <SplineDoubleKeyFrame KeyTime="00:00:00.7120000" Value="0" />
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="circle0"
                    Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
                <SplineDoubleKeyFrame KeyTime="00:00:00" Value="1" />
                <SplineDoubleKeyFrame KeyTime="00:00:00.0050000" Value="1" />
                <SplineDoubleKeyFrame KeySpline="0,0,0.601999998092651,0.400999993085861"
                        KeyTime="00:00:00.7000000" Value="0.3" />
                <SplineDoubleKeyFrame KeyTime="00:00:00.7120000" Value="0.30000001192092896" />
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="circle0"
                    Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
                <SplineDoubleKeyFrame KeyTime="00:00:00" Value="1" />
                <SplineDoubleKeyFrame KeyTime="00:00:00.0050000" Value="1" />
                <SplineDoubleKeyFrame KeySpline="0,0,0.601999998092651,0.400999993085861"
                        KeyTime="00:00:00.7000000" Value="0.3" />
                <SplineDoubleKeyFrame KeyTime="00:00:00.7120000" Value="0.30000001192092896" />
            </DoubleAnimationUsingKeyFrames>
</Storyboard>

Step 4: Add animation start and stop code

Add below code in your ProgressBar.xaml.cs file. This has a dependency property IsActive. When IsActive is set to true the Busy Indicator animation will start and when it is set to false the animation will be stopped.

public partial class ProgressBar : UserControl
{
    private Storyboard storyBoard;
    private List<Storyboard> storyBoardList;
    private int nextStoryBoard;
    public static readonly DependencyProperty IsActiveProperty =
            DependencyProperty.Register("IsActive", typeof(bool), typeof(ProgressBar), new PropertyMetadata(IsActivePropertyChanged));
    public ProgressBar()
    {
          InitializeComponent();
          this.storyBoard = new Storyboard()
          {
                   Duration = new Duration(TimeSpan.FromMilliseconds(100))
          };
           this.storyBoard.Completed += new EventHandler(this.OnIntervalTimerCompleted);
           this.storyBoardList = new List<Storyboard>()
          {
                   ProgressStoryboard0,
                   ProgressStoryboard1,
                   ProgressStoryboard2,
                   ProgressStoryboard3,
                   ProgressStoryboard4,
                   ProgressStoryboard5,
                   ProgressStoryboard6,
                   ProgressStoryboard7,
                   ProgressStoryboard8,
                   ProgressStoryboard9
          };
    }
    public bool IsActive
    {
        get { return (bool)GetValue(IsActiveProperty); }
        set { SetValue(IsActiveProperty, value); }
    }
    private static void IsActivePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var spinControl = sender as ProgressBar;
        if (spinControl != null)
        {
            if ((bool)e.NewValue)
           {
               spinControl.Start();
          }
          else
          {
              spinControl.Stop();
          }
        }
    }
    private void Start()
    {
        this.Visibility = Visibility.Visible;
        StartAnimation.Begin();
        this.storyBoard.Begin();
    }
    private void Stop()
    {
        this.Visibility = Visibility.Collapsed;
        StartAnimation.Stop();
        this.nextStoryBoard = 0;
        this.storyBoard.Stop();
        foreach (var item in this.storyBoardList)
        {
            item.Stop();
        }
    }
    private void OnIntervalTimerCompleted(object sender, EventArgs e)
    {
        this.storyBoardList[nextStoryBoard].Begin();
        this.nextStoryBoard = this.nextStoryBoard > 8 ? 0 : this.nextStoryBoard + 1;
        this.storyBoard.Begin();
    }
}

At this point you have completed coding for BusyIndicator control. Now the next step is implementation to see how exactly it works.

Step 5: Implementing Busy Indicator

To implement and test the above mentioned Busy Indicator, I have added a simple WCF MathService which returns sum of two values supplied to its Add method. The main reason behind choosing WCF service for this example is, this is the most common scenario to implement Busy Indicator.  Add service reference of this service into Silverlight project.MainPage.xaml changes:
Add namespace for Busy Indicator in MainPage.xaml file.

xmlns:progressBar="clr-namespace:CustomProgressBar"

And add below code in the same file.

<Grid x:Name="LayoutRoot" Margin="20,20,20,20">
        <Grid Margin="5,5,5,5">
            <StackPanel HorizontalAlignment="Center">
                <TextBlock x:Name="lblResult" />
                <Button x:Name="btnAdd" Width="100" Content="Add" Click="btnAdd_Click" />
            </StackPanel>
        </Grid>
        <progressBar:ProgressBar x:Name="ProgressBar1" Visibility="Collapsed"/>
</Grid>

You can see in above code, I have placed custom Busy Indicator control in MainPage using below line of code.

<progressBar:ProgressBar x:Name="ProgressBar1" Visibility="Collapsed"/>

MainPage.xaml.cs change: Add below code in this file.

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
    ProgressBar1.IsActive = true;
    MathService.MathServiceClient proxy = new CustomProgressBar.MathService.MathServiceClient();
    proxy.AddCompleted += new EventHandler<CustomProgressBar.MathService.AddCompletedEventArgs>(proxy_AddCompleted);
    proxy.AddAsync(10, 10);
}
void proxy_AddCompleted(object sender, CustomProgressBar.MathService.AddCompletedEventArgs e)
{
    lblResult.Text = e.Result.ToString();
    ProgressBar1.IsActive = false;
}

Here I have added a button with the name "Add", on click of this button I am calling MathService to calculate sum of two given numbers. Once the result is returned from MathService it will be displayed in TextBlock.  On button click event I am setting Progress Bar IsActive property to true, at this moment the Busy Indicator animation will start. And when the Add method completed event is called I am setting IsActive property value to false, to stop the animation.

Step 6: Run the application

Once all the changes are completed run the application. You will see below screen when you click on "Add" button. The good thing is, until the Busy Indicator runs the UI portion of the application will be locked and once the processing is completed screen will be unlocked again.

HostForLIFE.eu Silverlight 6 Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Silverlight 6 Hosting Romania - HostForLIFE.eu :: How to Create Storyboard Animation using Expression Blend in Silverlight

clock June 30, 2015 06:11 by author Rebecca

There are two ways to animate in Silverlight, through storyboards and through code. Expression Blend offers extensive help in creating storyboard animations. Silverlight animation is time based not frame based, this means that your animation will benefit from running at the maximum frame rate that the users machine will allow. Multiple storyboards can be created and run at the same time, but for the purpose of this basic tutorial, you'll be shown how to create a single storyboard.

Follow these simple steps to create storyboard animation using expression blend in Silverlight:

Step 1

To create a new storyboard, go to the Objects and Timeline tab then click on the ‘plus’ icon.

If you are using the default UI layout in Blend, you may want to hit the ‘F6‘ key to switch the layout from design mode to animation mode, this will give you a better layout for working with storyboards.

Notice that after adding a storyboard a red circle will be displayed in the top right of the screen, this indicates that you are in record mode. When in record mode, every change you make is treated as an animation and will be tied to a Keyframe. To turn record mode on or off click on the red circle in the top right of the screen, it should toggle from red to grey.

Step 2

For the purpose of this tutorial I have created a ball graphic and a shadow graphic as shown below. You can use any objects thay you like to make your own animation project.  I have placed them off the page to the left so that they start out of site.

Step 3

Storyboard animation is based on Keyframes set to specific times. To add a Keyframe, go back to the ‘Objects and Timeline‘ tab, select the objects that you want to animate and click the Record Keyframe button as highlighted below. You will see that a new Keyframe is added by each object at zero seconds.

Step 4

To add a Keyframe at a specific point along your timeline, drag the yellow time bar to the required point and then hit the Record Keyframe button. To make our ball graphic animate I have selected a time stamp of 0.5 seconds and moved the ball to the position shown below:

Step 5

Then you can animate the ball and shadow graphics again at 1 second.

And once more at 1.5 seconds to finish the animation.

Step 6

Now that we have completed the animation we may want to loop it multiple times or loop it forever. To make the animation loop, make sure you have the storyboard selected under the ‘Objects and Timeline‘ tab, then go to your ‘Properties‘ tab and scroll down to the ‘Common Properties‘ section. Here you have an option to repeat the animation several times, for this tutorial, you have to set it to ‘Forever‘.

Step 7

Finally, you need to tell the storyboard to play. Sometimes you will need a storyboard to be called by the code behind file, but you can use ‘Behaviors’ to start a storyboard instead. ‘Behaviors’ are pre-set actions that can be dropped onto objects in Blend, they are an easy way to achieve functionality without requiring knowledge of C# or alternative languages. To tell the storyboard to autoplay, go to the ‘Assets‘ button on the main tool bar (the last icon), select ‘Behaviors‘ from the list on the left to bring up the selection of behaviors. Find the behavior titled ‘ControlStoryboardAction‘ and drag it onto your ‘LayoutRoot‘. See how the behavior is indented below the ‘LayoutRoot‘. Select the behavior and go to the ‘Properties‘ tab, scroll down to the ‘Triggers‘ section and set the following settings:

EventName = Loaded

ControlStoryboard… = Play

Storyboard = Storyboard1 (the name of your storyboard)

You are done with your storyboard animation!

HostForLIFE.eu Silverlight 6 Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in