European Silverlight 4 & Silverlight 5 Hosting BLOG

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

Silvelight 6 Hosting - HostForLIFE.eu :: How to pass init parameters in Silverlight?

clock March 7, 2024 07:27 by author Peter
In your aspx page where object tag is present..Add init param tag of your own.

<object data="data:application/x-silverlight-2,"  ID="Silverlight2"  type="application/x-silverlight-2" width="100%" height="100%">
          <param name="source" value="ClientBin/ProductProDemo.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="4.0.41108.0" />
          <param name="autoUpgrade" value="true" />  
                    
          <param name="initParams"  value="startPage='<asp:Literal id="id" runat="server"/>'"></param>
           
          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.41108.0" style="text-decoration:none">
               <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
          </a>
        </object>

In the code behind file of the same aspx page ie aspx.cs file..

On page load provide the value to your init param
protected void Page_Load(object sender, EventArgs e)
{        
    id.Text = "Page1".ToString();        
}


In your App.xaml.cs file you can access the value as 
private void Application_Startup(object sender, StartupEventArgs e)
{
    string startPage = e.InitParams["startPage"];             
    this.RootVisual = new MainPage();
}

 



Silvelight 6 Hosting - HostForLIFE.eu :: Implementing INotifyPropertyChanged in Silverlight

clock May 26, 2023 08:15 by author Peter

Data binding is one of the best features the human race has ever devised. Binding a property of a UI Element to a property in the code behind can accomplish any task. It is magic, in a nutshell. Once the properties are bound, we must continue to notify the UI whenever the property's value is modified in the code. INotifyPropertyChanged is useful in this situation.


Because it is an interface, it must first be implemented. However, the procedure is not arduous. Here is the code for my primary page in my new Silverlight project:

publicpartialclassMainPage : UserControl
{
    privatestring _names;
     publicstring Names
    {
        get
        {
            return _names;
        }
        set
        {
            _names = value;
        }
    }

    public MainPage()
    {
        InitializeComponent();
    }

    privatevoid MainPage_OnLoaded(object sender, RoutedEventArgs e)
    {
        Names = "This is the Text";
    }
}


The property "Name" I have here is bound with the textblock in XAML, here is the code:
<UserControlx:Class="PropertyChangedDescribed.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"
 Loaded="MainPage_OnLoaded"
 x:Name="TestingPropertyChanged"
 d:DesignHeight="300"d:DesignWidth="400">

 <Gridx:Name="LayoutRoot"Background="White">
  <TextBlockText="{Binding Names, ElementName=TestingPropertyChanged}"/>
  </Grid>

</UserControl>

As you can see, the textblock has it's "text" property bound with our code behind's property "Name". Right now, no matter what you set the value of "Name", it will never be reflected onto the UI. So, what we want is, every time we change the value of our property "Name," the text block has its value changed too. In order to do this, we need to implement the interface INotifyPropertyChanged. Here is the modified main page's code to do so:
publicpartialclassMainPage : UserControl, INotifyPropertyChanged
{
    privatestring _names;
    publicstring Names
    {
        get
        {
            return _names;
        }
        set
        {
            _names = value;
            OnPropertyChanged("Names");
        }
    }
    public MainPage()
    {
        InitializeComponent();

    }

    privatevoid MainPage_OnLoaded(object sender, RoutedEventArgs e)
    {
        Names = "This is the Text";

    }

    publicevent PropertyChangedEventHandler PropertyChanged;
    privatevoid OnPropertyChanged(string propertyName)

    {
        if (this.PropertyChanged != null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
        }
    }
}


So this is how you can implement INotifyPropertyChanged in Silverlight.



Silvelight 6 Hosting - HostForLIFE.eu :: How to Move Image or Object in Silverlight ?

clock December 18, 2020 08:25 by author Peter

The control that you just like drag or move with the mouse is embedded among a Border control then handle the mouse down, up and move events to create the object move among your layout panel.

See sample .xaml code:
<Canvas x:Name="LayoutRoot" Background="White">
<Border x:Name="border1"
Canvas.Top="100"
Canvas.Left="10"
MouseLeftButtonDown="border1_MouseLeftButtonDown"
MouseLeftButtonUp="border1_MouseLeftButtonUp"
MouseMove="border1_MouseMove"> 
<Image x:Name="MyImage" Source="images/Basket.png" Stretch="Uniform" ></Image>           
</Border>
</Canvas>


In the above code, a Border control is placed within the Canvas. The foremost necessary code to notice is:
MouseLeftButtonDown="border1_MouseLeftButtonDown"
MouseLeftButtonUp="border1_MouseLeftButtonUp"
MouseMove="border1_MouseMove"


The above lines outline 3 events that we tend to like to handle. because the name indicates, we are handling the mouse button down, mouse button up and mouse move events for the left mouse.

In the code behind, once the left button is pressed, we are going to set a global variable to point that user has started moving. within the mouse move event, we are going to get the current location of the mouse pointer and then set the new position for the border control. once the left mouse button is discharged, we are going to reset the global variable in order that we are going to not move the item from now on.
See the code for the code behind class:
public partial class Page : UserControl
{
// Global variable to indicate if user has clicked border
// and started/stopped moving.
private bool moving = false;
private double offSetX;
private double offSetY;
public Page()
{
InitializeComponent();
}

private void border1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Left mouse button clicked within border. start moving.
moving = true;

Point offset = e.GetPosition(border1);
offSetX = offset.X;
offSetY = offset.Y;
}

private void border1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// Left mouse button release. Stop moving.
moving = false;
}

private void border1_MouseMove(object sender, MouseEventArgs e)
{
if (moving)
{
    // Get the new mouse pointer position
    Canvas parent = (Canvas)this.border1.Parent;
    Point p = e.GetPosition(parent);
    double x = p.X - offSetX;
    double y = p.Y - offSetY;
    // Set the new position for the border control.
    this.border1.SetValue(Canvas.LeftProperty, x);
    this.border1.SetValue(Canvas.TopProperty, y);
}
}
}

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 :: Code to download pdf file in silverlight

clock July 26, 2019 11:08 by author Peter

Hi, I want to download a pdf file form silverlight application , the pdf file is in a folder in my solution , i want to give the path of the pdf to the method and it should download the pdf to the local system. i am happy to say that i achieved it with the following code:
SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "pdf Files|*.pdf";
                dialog.DefaultFileName = "BeneficiaryDesignation.pdf";
                if (dialog.ShowDialog() ?? false)
                {


                    WebClient webClient = new WebClient();
                    webClient.OpenReadCompleted += (s, e2) =>
                    {
                        try
                        {
                            using (Stream fs = (Stream)dialog.OpenFile())
                            {
                                e2.Result.CopyTo(fs);
                                fs.Flush();
                                fs.Close();
                            }
                           
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    };
                    string str = App.Current.Host.Source.AbsoluteUri;
                    string path = App.appConfiguration.GetPDFPath("BeneficiaryDesignation.pdf");
                    str = str.Replace("/ClientBin/ProjectDemo.xap", path);                    
                   
                    webClient.OpenReadAsync(new Uri(str), UriKind.RelativeOrAbsolute);
                }

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 5 Hosting France - HostForLIFE.eu :: Create an Exception Logger in Silverlight

clock June 21, 2019 11:42 by author Peter

In this post I'll describe the way to handle the exceptions in Silverlight. Whereas running the Silverlight application, if any exception happens it'll attend Silverlight.js and show within the internet explorer as a javascript error. Within the debugging purpose of read typically it's cumbersome to see wherever truly the exception happened.

LogWindow.xaml
This is an easy user control that has an easy textbox:
<TextBox
AcceptsReturn="True"
TextAlignment="Left"
TextWrapping="NoWrap"
VerticalScrollBarVisibility="Visible"
x:Name="logText"
FontFamily="Courier New"
FontSize="12" IsReadOnly="True" HorizontalScrollBarVisibility="Auto" />

Logger.cs
This class are used to print the exception and notice the stacktrace. it's an enum for the exception types viz. DEBUG,INFO,WARN,ERROR and FATAL.This class contains an easy delegate to add text to the log window.
The static property _instance is about by the LogWindow.xaml.cs go in the load event as:
Logger._instance = logText;
So that it will print whatever exception happenes in your application. The LogException methodology expects exception object because the parameter and find the exception information using the StackFrame class.

StackFrame frame = new StackFrame(true);
callerSignature =  string.Format("@{0}:{1}:{2}", frame.GetMethod(), frame.GetFileName(), frame.GetFileLineNumber());


To use this method in your catch block you just simply need to call the static method as:
Catch(Exception ex)
{
Logger.LogException(ex);
}

Hope this tutorial works for you!



Silverlight 6 Hosting - HostForLIFE.eu :: Print Document In Silverlight

clock May 23, 2019 05:30 by author Peter

How we can print the document in a Silverlight application.

Step 1
We have the PrintDocument Class which defines a reusable object that sends output to a printer.
    PrintDocument
    The PrintDocument object encapsulates all the information needed to print a page. They associate with the control which content can be print. They handle the events and operations of printing.
    Namespace - System.Drawing.Printing.PrintDocument

    [C#]

    public class PrintDocument : Component

    
We can create an instance of the PrintDocument class, set the properties that describe how to print, and call the Print method to start the printing process. Handle the PrintPage event where you specify the output to print, by using the Graphics included in the PrintPageEventArgs.
    Associate control to Print document
        private void printDoc_PrintPage(object sender, PrintPageEventArgs e) { 
            // print current page 
            e.PageVisual = printPage; 
        } 


Step 2
Create one user control page name as PrintPage.Xaml and design header and footer in this user control page like as following.
    <Grid x:Name="LayoutRoot" Background="White"> 
        <Grid.RowDefinitions> 
            <RowDefinition Height="Auto" /> 
            <RowDefinition /> 
            <RowDefinition Height="Auto" /> 
        </Grid.RowDefinitions> 
        <!--Header--> 
        <Grid> 
            <TextBlock Text="HEADER" /> 
        </Grid> 
        <!--Body--> 
        <ItemsControl Name="BodyItemsControl" Grid.Row="1" Margin="0,24" /> 
        <ItemsControl Name="TemplateItemsControl"> 
            <ItemsControl.ItemTemplate> 
                <DataTemplate> 
                    <Grid> 
                        <Grid.ColumnDefinitions> 
                            <ColumnDefinition Width="Auto" /> 
                            <ColumnDefinition Width="Auto" /> 
                            <ColumnDefinition Width="*" /> 
                        </Grid.ColumnDefinitions> 
                        <TextBlock Text="{Binding ID}" Margin="2" /> 
                        <TextBlock Text=" - " Grid.Column="1" Margin="2" /> 
                        <TextBlock Text="{Binding Description}" Grid.Column="2" TextWrapping="Wrap" MaxWidth="500" HorizontalAlignment="Left" Margin="2" /> 
                    </Grid> 
                </DataTemplate> 
            </ItemsControl.ItemTemplate> 
        </ItemsControl> 
        <Grid Grid.Row="2"> 
            <TextBlock Text="FOOTER" /> 
        </Grid> 

Step 3
In MainPage.Xaml create an instance of PrintDocument like as following.
    public MainPage() { 
        InitializeComponent(); 
        this.Loaded += new RoutedEventHandler(MainPage_Loaded); 
    } 
    void MainPage_Loaded(object sender, RoutedEventArgs e) { 
        GetItems(); 
        printDoc.PrintPage += newEventHandler < PrintPageEventArgs > (printDoc_PrintPage); 
    } 
    //following items for printing. 
    privatevoid GetItems() { 
        for (int i = 0; i < 100; i++) { 
            items.Add(newItem() { 
                ID = i, 
                    Description = "This is Print Document " + i 
            }); 
        } 
    } 
    //Handling the event when we're printing: 
    private void printDoc_PrintPage(object sender, PrintPageEventArgs e) { 
        PrintPage printPage = new PrintPage(); 
        // print current page 
        e.PageVisual = printPage; 
        e.HasMorePages = true; 
        break; 
    } 
 

Step 4
Add a button to the MainPage.Xaml and print the document when the button is clicked,
    <Button Content="Button" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="42,56,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> 
    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
        printDoc.Print("Printing A Page"); 
    } 


Step 5

Output look like as following,

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 Hosting France - HostForLIFE.eu :: Use ScrollViewer Layout Panel in Silverlight

clock May 17, 2019 11:36 by author Peter

In this post allow us to understand how to use ScrollViewer panel Layout inside a Silverlight application. ScrollViewer is an additional layout container, that we don’t use constantly. It's chiefly useful showing contents in an exceedingly scrollable panel such as ListBox or Editor window. ListBox, TextBox, RichTextBox internally uses ScrollViewer to implement the scrolling functionality. Allow us to discuss the implementation in this post.

As usual, open up visual studio and choose Silverlight project. We will discover there's a Grid layout in your MainPage. xaml. Eliminate the default Grid layout and merely drag and drop the Stack panel Layout into our application. The code for this looks such as:
<StackPanel x:Name="LayoutRoot" > </StackPanel>

Inside the stack panel I am just defining 12 different rectangles.  And this is the code that I used:
<StackPanel x:Name="LayoutRoot" Orientation="Vertical" Width="100">
            <Rectangle Height="50" Width="100" Fill="Red" />
            <Rectangle Height="50" Width="100" Fill="Green" />
            <Rectangle Height="50" Width="100" Fill="Orange" />
            <Rectangle Height="50" Width="100" Fill="Tomato" />
            <Rectangle Height="50" Width="100" Fill="WhiteSmoke" />
            <Rectangle Height="50" Width="100" Fill="Green" />
            <Rectangle Height="50" Width="100" Fill="Blue" />
            <Rectangle Height="50" Width="100" Fill="Yellow" />
            <Rectangle Height="50" Width="100" Fill="Azure" />
            <Rectangle Height="50" Width="100" Fill="Gold" />
            <Rectangle Height="50" Width="100" Fill="Blue" />
            <Rectangle Height="50" Width="100" Fill="Violet" />
        </StackPanel>


In case we compile the above code as it's, we will notice all of the rectangles however no scroll bar result. Thus in an effort to get scroll bar effect we ought to put the above stack panel inside scroll viewer and ought to offer fixid width towards the scroll viewer. And this is the code snippet:
<ScrollViewer Height="200" >
        <StackPanel x:Name="LayoutRoot" Orientation="Vertical" Width="100">
            <Rectangle Height="50" Width="100" Fill="Red" />
            <Rectangle Height="50" Width="100" Fill="Green" />
            <Rectangle Height="50" Width="100" Fill="Orange" />
            <Rectangle Height="50" Width="100" Fill="Tomato" />
            <Rectangle Height="50" Width="100" Fill="WhiteSmoke" />
            <Rectangle Height="50" Width="100" Fill="Green" />
            <Rectangle Height="50" Width="100" Fill="Blue" />
            <Rectangle Height="50" Width="100" Fill="Yellow" />
            <Rectangle Height="50" Width="100" Fill="Azure" />
            <Rectangle Height="50" Width="100" Fill="Gold" />
            <Rectangle Height="50" Width="100" Fill="Blue" />
            <Rectangle Height="50" Width="100" Fill="Violet" />
        </StackPanel>
    </ScrollViewer>

Finally, Run the code and here is the result:



European Silverlight 6 Hosting HostForLIFE.eu :: How to access controls in DataGrid TemplateColumn header?

clock April 25, 2019 11:20 by author Peter

A data grid view is a rectangular control made of columns and rows. I have a DataGrid where I have included some controls in column header. Each column is a Template column. These controls appear just below the column header which are used for entering filter information. Here's the issue on my code on Silverlight 5.


VisualTreeHelper class helps to iterate through the visual tree of the xaml. Using it we can find the child and parent controls of the rendered controls. Lets check the Visual Tree of the rendered control using Silverlight Spy.

The Following Method do a search over the child controls with in a control recursively and returns the control based on Name.

private object GetChildControl(DependencyObject parent, string controlName)

    Object tempObj = null;
    int count = VisualTreeHelper.GetChildrenCount(parent);
    for (int counter = 0; counter < count; counter++)
    {
        //Get The Child Control based on Index
        tempObj = VisualTreeHelper.GetChild(parent, counter);
        //If Control's name Property matches with the argument control
        //name supplied then Return Control
        if ((tempObj as DependencyObject).GetValue(NameProperty).ToString() == controlName)
            return tempObj;
        else //Else Search Recursively
        {
            tempObj = GetChildControl(tempObj as DependencyObject, controlName);
            if (tempObj != null)
                return tempObj;
        }
    }
    return null;
}

Make sure that the same has to be delegated to UI thread using Dispatcher. As the controls created using UI Thread can not be accessed from other thread.
//Access the Grid Header Controls
Dispatcher.BeginInvoke(delegate
{
    var hyperlinkControl = GetChildControl(dataGrid1, "hlSort");
    var checkControl = GetChildControl(dataGrid1, "chkSelectAll");
});



European Silverlight 6 Hosting :: Retrieving Data in Silverlight: Where is my data?

clock March 27, 2019 09:46 by author Peter

So I was plugging right along in Silverlight using LINQ to asynchronously pull data from our database into my C# code. Everything was going great until I attempted to pull data from one table and its related tables all in one query. Here is what I found which resolved my data problem.

In my Library class I have the following code that enables my ASP.NET code to query a User by UserID and return a User object along with their UserFavorites and Illustration objects. This gives me everything I need to know about the user and their favorite illustrations.
public IQueryable<MyLibrary.User> GetUserByID(int userID)

{
    return myContext.Users.Include("UserFavorites").Include("UserFavorites.Illustration")
        .Where(u => u.UserID == userID);
}

In Silverlight I had a need to perform the same query using LINQ. After much searching on the web I found the two things that were needed to make this happen.
1. Use "Expand" instead of "Include"

2. Instead of "UserFavorites.Illustration" replace the "." with a "/" to get "UserFavorites/Illustration".

    int userID = 0;
    var qUser = ((DataServiceQuery<User>)(from myUser in service.Users
                  where myUser.UserID.Equals(userID)
                  select myUser))
                .Expand("UserFavorites")
                .Expand("UserFavorites/Illustration");

Now I have all of my data and I am happy once again. Using the Expand on my query is very nice in that I can get all of my data in one asynchronous call.

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 :: Create an Analog Clock application in Silverlight

clock March 22, 2019 11:17 by author Peter

Today, I will explain you how to create an analog clock apps in Silverlight 6. Of course open new projectin visual studio and select a Silverlight project. In Mainpage.xaml  draw an ellipse which will serve as background for our Analog clock. The code looks as following:

 

<Grid x:Name="LayoutRoot" Background="White">
        <Ellipse Margin="165,67,145,83" Fill="Goldenrod" Width="330"
         Height="330" Opacity="0.7"/>
    </Grid>

Then, draw another ellipse in the same grid which will serve as Outer Rim for our analog clock. The Complete code looks on the below:
<Ellipse Height="330" Margin="156,58,154,92" Width="330" 
Stroke="Goldenrod">
            <Ellipse.Fill>
<LinearGradientBrush EndPoint="0.84,0.87" Opacity="0.9"  
StartPoint="0.164,0.129">
                    <GradientStop Color="Goldenrod"/>
                    <GradientStop Color="Gold" Offset="0.7"/>
                </LinearGradientBrush>
            </Ellipse.Fill>
        </Ellipse>              


Next, I want to draw another ellipse in the same grid which will serve as Bevel for our analog clock. And this is the code that I used:
        <Ellipse Height="290" Margin="156,58,154,92" Width="290" Stroke="Goldenrod">
            <Ellipse.Fill>
                    <LinearGradientBrush EndPoint="0.84,0.87" Opacity="0.5" StartPoint="0.164,0.129">
                    <GradientStop Color="Goldenrod"/>
                    <GradientStop Color="Goldenrod" Offset="0.987"/>
                </LinearGradientBrush>
            </Ellipse.Fill>
        </Ellipse>     

Now draw another ellipse in the same grid which will serve as a Face for our analog clock. This is the code snippet:
<Ellipse Height="270" Margin="176,78,174,112" Width="270"
         Stroke="Goldenrod" Fill="Yellow" Opacity="0.3"/>

Now we are going to draw the hour,minute and seconds hand. Then draw a rectangle in the same grid which will serve as a Hour hand for our analog clock with the code below:
<Rectangle x:Name="hourHand" Height="59" Margin="315.75,180,314.25,0"
        VerticalAlignment="Top" Fill="Black" Stroke="Black" Width="10" RenderTransformOrigin="0.525,1.428">
            <Rectangle.RenderTransform>
                <RotateTransform x:Name="hourHandAnimation"/>
            </Rectangle.RenderTransform>
        </Rectangle>


Now draw another rectangle in the same grid which will serve as a Minute hand for our analog clock. And this is the code that I used:
<Rectangle x:Name="minuteHand" Height="80" Margin="316.75,160,315.25,0"       
VerticalAlignment="Top" Fill="Black" Stroke="Black" Width="8"
        RenderTransformOrigin="0.5,1.312" >
            <Rectangle.RenderTransform>
                <RotateTransform x:Name="minuteHandAnimation"/>
            </Rectangle.RenderTransform>
        </Rectangle>

Now we are going to draw another rectangle in the same grid which will serve as a Seconds hand for our analog clock. And this is the code that I used:
<Rectangle Height="80" Margin="318.25,160,316.75,0"
        VerticalAlignment="Top" Fill="#FFFF0000" Stroke="#FF000000"
        Width="5" RenderTransformOrigin="0.10,1.312" >
            <Rectangle.RenderTransform>
                <RotateTransform x:Name="secondHandAnimation"/>
            </Rectangle.RenderTransform>
        </Rectangle>

Now, our design part is complete. Now we have to give animations to our hour, minute and second’s hands. For this, let us take a storyboard. We should write the code for storyboard outside the Grid.  The complete code for all the three animations is as follows.
<UserControl.Resources>
        <Storyboard x:Name="silverlightClock">
            <DoubleAnimation x:Name="hourAnimation"                            
                             Storyboard.TargetName="hourHandAnimation"
                             Storyboard.TargetProperty="Angle"
                             Duration="12:0:0" RepeatBehavior="Forever" To="360"/>          
            <DoubleAnimation x:Name="minuteAnimation"
                             Storyboard.TargetName="minuteHandAnimation"
                             Storyboard.TargetProperty="Angle"
                             Duration="1:0:0" RepeatBehavior="Forever"/>                                                                
            <DoubleAnimation x:Name="secondAnimation"                            
                             Storyboard.TargetName="secondHandAnimation"
                             Storyboard.TargetProperty="Angle"
                             Duration="0:1:0" RepeatBehavior="Forever"/>                                   
 </Storyboard>
 </UserControl.Resources>

Now we have to write the code for these 3 animations (hourAnimation, minuteAnimation  and secondAnimation ) in MainPage.xaml.cs. The code looks as follows.
private void startClock(object sender, RoutedEventArgs e)
        {
            System.DateTime currentTime = DateTime.Now;
double hourAngle = ((float)currentTime.Hour) / 12 * 360 +                 
currentTime.Minute/2;          
hourAnimation.From = hourAngle;
            hourAnimation.To = hourAngle + 360;         
           double minuteAngle = ((float)currentTime.Minute) / 60 * 360;
            minuteAnimation.From = minuteAngle;
            minuteAnimation.To=minuteAngle+360;
           double secondAngle = ((float)currentTime.Second) / 60 * 360;
            secondAnimation.From = secondAngle;
            secondAnimation.To = secondAngle + 360;
            silverlightClock.Begin();
        }                          

We need to call the method “startClock” in our grid control and assign it to “Loaded” property of the grid control. The code for this looks as follows.
  <Grid x:Name="LayoutRoot" Background="White" Loaded="startClock"> 
</Grid>


Finally! Our Analog clock is ready. Now you should refresh and see it.

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