European Silverlight Hosting BLOG

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

Silvelight 6 Hosting - HostForLIFE.eu :: A Simple Silverlight Application Implementing MVVM

clock May 21, 2021 08:36 by author Peter

A Simple Silverlight Application Implementing MVVM

MVVM

In simple words, View knows ViewModel, ViewModel knows Model, but not vice versa.

Why MVVM
    Easy to unit test.
    No need to change model to support changes in View.
    Very minor changes required in ViewModel to support changes in View.
    Separates UX designer and developer i.e the development team can focus on creating ViewModel classes, and the design team can focus on making user-friendly Views.

Simple Silverlight application using MVVM

Here I am just going to get a student name and age from the user and display the details in a GridView as in the figure.

The important areas covered are MVVM, using Relay Command and IValueConverter.

Creating a Student class

I created student class with the following properties, Name, Age, JoiningDate.
using System;
using System.Net;
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 MVVMDemoinSL
{
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime JoiningDate { get; set; }
    }
}


Creating ViewModelBase and ViewModel class

It's always a good idea to have a ViewModelBase class and inherit all the ViewModels from that. Hence we can reuse the code for implementing INotifyPropertyChanged.

The main purpose of using INotifyPropertyChanged is to get notification whenever the property value is changed.
I created a ViewModelBase as below.
using System;
using System.Net;
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;
using System.ComponentModel;

namespace MVVMDemoinSL
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

I also created a ViewModel class which inherits from ViewModelBase.
using System;
using System.Net;
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;
using System.Collections.ObjectModel;

namespace MVVMDemoinSL
{
    public class ViewModel : ViewModelBase
    {
        private Student _student;
        private ObservableCollection<Student> _students;
        private ICommand _SubmitCommand;
        public Student Student
        {
            get
            {
                return _student;
            }
            set
            {
                _student = value;
                NotifyPropertyChanged("Student");
            }
        }

        public ObservableCollection<Student> Students
        {
            get
            {
                return _students;
            }
            set
            {
                _students = value;
                NotifyPropertyChanged("Students");
            }
        }

        public ICommand SubmitCommand
        {
            get
            {
                if (_SubmitCommand == null)
                {
                    _SubmitCommand = new RelayCommand(Submit);
                }
                return _SubmitCommand;
            }
        }

        public ViewModel()
        {
            Student = new Student();
            Students = new ObservableCollection<Student>();
            Students.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Students_CollectionChanged);
        }
        //Whenever new item is added to the collection, am explicitly calling notify property changed

        void Students_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            NotifyPropertyChanged("Students");
        }

        private void Submit()
        {
            Student.JoiningDate = DateTime.Today.Date;
            Students.Add(Student);
            Student = new Student();
        }
    }
}


RelayCommand
Since we are following the MVVM pattern, instead of having a Button click event in code behind, we are going to use the Command Property of the button. The RelayCommand allows you to inject the command's logic via delegates ed into its constructor. This approach allows for terse, concise command implementation in ViewModel classes. RelayCommand is a simplified variation of the DelegateCommand. RelayCommand implementation using CommandManager is not possible using Silverlight.
using System;
using System.Net;
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 MVVMDemoinSL
{
    public class RelayCommand : ICommand
    {
        private Func<bool> canExecute;
        private Action executeAction;
        public event EventHandler CanExecuteChanged;

        public RelayCommand(Action executeAction,
            Func<bool> canExecute)
        {
            this.executeAction = executeAction;
            this.canExecute = canExecute;
        }

        public RelayCommand(Action executeAction)
|        {
           this.executeAction = executeAction;
            this.canExecute = () => true;
        }

        public void RaiseCanExecuteChanged()
       {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }

        public bool CanExecute(object parameter)
         {
           return canExecute == null ? true : canExecute();
        }

        public void Execute(object parameter)
        {
            executeAction();
        }
    }
}

View

Now we have to create a view and bind it with ViewModel properties. The code for the view can be found below. I have used a window, Grid, Textbox, TextBlock, Button and GridView.
<UserControl x:Class="MVVMDemoinSL.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
              xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
             xmlns:viewmodel="clr-namespace:MVVMDemoinSL"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <viewmodel:ViewModel x:Key="ViewModel"/>
        <viewmodel:DatetimeToDateConverter x:Key="MyConverter"/>
    </UserControl.Resources>

    <Grid DataContext="{Binding Source={StaticResource ViewModel}}">
        <Grid.RowDefinitions>

            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" Text="Name" HorizontalAlignment="Center"/>
        <TextBox Grid.Row="0" Grid.Column="1" Width="100" HorizontalAlignment="Center" Text="{Binding Student.Name, Mode=TwoWay}"/>
        <TextBlock Grid.Row="1" Grid.Column="0" Text="Age" HorizontalAlignment="Center"/>
        <TextBox Grid.Row="1" Grid.Column="1" Width="100" HorizontalAlignment="Center" Text="{Binding Student.Age, Mode=TwoWay}"/>
        <Button Content="Submit" Command="{Binding SubmitCommand}" HorizontalAlignment="Right" Grid.Row="2" Grid.Column="0"/>
        <sdk:DataGrid ItemsSource="{Binding Students}" Grid.Row="3" Grid.Column="0" Width="200" AutoGenerateColumns="False">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="Name"  Binding="{Binding Name}" Width="60"/>
                <sdk:DataGridTextColumn  Header="Age" Binding="{Binding Age}" Width="60"/>
                <sdk:DataGridTextColumn Header="Joining Date" Binding="{Binding JoiningDate, Converter={StaticResource MyConverter}}" Width="80" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
    </Grid>
</UserControl>


If you see the above XAML code, you can see I am using Windows resources in my view. In resources, I am adding a reference to my ViewModel and DateTimeToDateConverter.

ValueConverter

We might often get some values from the property but we have to display some other value in the View. Say for example in my project, the Joining date is a date time value but I need to display only date. I can do this either by String format in binding or else ValueConverter. I just want to go with the latter one, since you can understand ValueConverter also.
using System;
using System.Net;
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;
using System.Windows.Data;
using System.Globalization;

namespace MVVMDemoinSL
{
    public class DatetimeToDateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime date = (DateTime)value;
            return date.ToString("MM/d/yyyy");
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }
}


For implementing MVVM in WPF, please go through the following article.



Silvelight 6 Hosting - HostForLIFE.eu :: PopUp Control In Silverlight

clock April 23, 2021 10:40 by author Peter

Pop Up Control is a Visual Prompt Control provided in Silverlight. There are certain times when you need to really grab the user's attention. Maybe you need to display details about a critical error. Then you can just use this control. This visual prompt is designed to simulate a dialog box.
In our Sample Application we will just demonstrate how to use it.

Create a Silverlight Project

Figure 1.1 Creating Silverlight Project

Designing the Application
Here is an idea, we will add three images (ImageControls) to our application and on theirs LeftMouseButtonDown Event we will display the PopUp. So I have taken the help of Blend 3 to design the application. It will have 3 Images as Home, Search and Reports. The following figure displays our application.

Figure 1.2 Designing our Application

Adding a PopUp Control
This is actually disturbing; you can't find the control in the toolbox. But if you start typing the control name it will satisfy you. So I have added some controls like Border, StackPanel and Displaying Text and Button to close the PupUp.
    <Popup x:Name="myPopup" Margin="-34,0,-31,0" Grid.Row="2" Grid.Column="1" Height="78" VerticalAlignment="Bottom"  >    <Border CornerRadius="10" Background="Silver" BorderThickness="2" BorderBrush="Black">  
        <StackPanel Margin="10">  
                    <TextBlock x:Name="PopUpText"/>  
                    <Button x:Name="PopUpButton" Height="30" Width="90" Content="Close" Click="PopUpButton_Click" />  
        </StackPanel>  
        </Border>  
    </Popup>  


PopUp Control has a unique property called IsOpen which returns a boolean value of either true or false. The default value is always false. With this concept in mind let's add some events and use this property to control the show of the PopUp.

Calling the PopUp Control
As we discussed earlier we can handle the display of the PopUp by using the property IsOpen. Now we will see how we have used in our sample application.
    private void PopUpButton_Click(object sender, RoutedEventArgs e)  
    {  
          myPopup.IsOpen = false;  
    }  
      
    private void Home_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
    {  
          PopUpText.Text = "You Clicked Home";  
          myPopup.IsOpen = true;  
    }  
      
    private void Search_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
    {  
          PopUpText.Text = "You Clicked Search";  
          myPopup.IsOpen = true;  
    }  
      
    private void Reports_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
    {  
          PopUpText.Text = "You Clicked Reports";  
          myPopup.IsOpen = true;  
    }  


Running the Application
When you click different images you will be notified by the PopUp Control.

Figure 1.3 PopUp is displayed

That's it, we have successfully used the PopUp Control. Enjoy Coding.



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 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 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.



Silverlight 6 Hosting UK - HostForLIFE.eu :: INotifyPropertyChanged in Silverlight

clock January 9, 2019 11:35 by author Peter

Data binding is one of the coolest gimmicks that have ever existed in Silverlight. Binding a UI Element's property with a property in the code behind, has the ability to do any sort of trap. It's wizardry, basically. Once the properties are bound, we have to continue telling the UI if the property's estimation has been adjusted in the code. INotifyPropertyChanged is helpful for this.

You see, since it is an interface, we have to first actualize it. The procedure is not exceptionally extreme however. In the new Silverlight project, here is the code of my main page:
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. Now write the following 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 should be obvious, the textblock has its "text" property bound with our code behind's property "Name". At this moment, regardless of what you set the estimation of "Name", it will never be reflected onto the UI. Thus, what we need is, each time we change the estimation of our property "Name," the content piece has its esteem changed as well. To do this, we have to actualize the interface INotifyPropertyChanged. Here is the changed primary page's code to do as such:
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));
        }
    }
}

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 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.



About HostForLIFE

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

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


Tag cloud

Sign in