Advanced Tutorials

[TUTORIAL][WP8]Simple BMI(Body Mass Index) Calculator App In C# XAML

This app is a very basic and is very easy to understand the working and handling I/O errors.Also parsing the required variable calculating the required thing and displaying the output is also included.

Also passing the value of a variable from one page to another is included in this project.

Download the attached project file for the tutorial.Open the project in visual studio.

[TUTORIAL]Adding Animations Dynamically(Programmatically) in C# XAML

This tutorial describes the procedure to add animation dynamically instead of xaml so that you can interact with the UI elements via Backend Code.

The MainPage.xaml code is here:

<Page
x:Class=”App12.MainPage”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
xmlns:local=”using:App12″
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243;
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;
mc:Ignorable=”d”>

<Canvas Name=”LayoutRoot” Background=”{StaticResource ApplicationPageBackgroundThemeBrush}”/>
</Page>

App12(bold letter) is my project name so the name of the project you gave will appear here.

The Backend Coding i.e MainPage.xaml.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Shapes;
using Windows.UI;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace App12
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();

Grid grid = new Grid();

RotateTransform rotatetransform = new RotateTransform();
rotatetransform.Angle = 0;
rotatetransform.CenterX = 50;
rotatetransform.CenterY = 50;

TranslateTransform translatetransform = new TranslateTransform();
translatetransform.X = 0;
translatetransform.Y = 0;

Ellipse myRectangle = new Ellipse(); //Sorry I didnt rename the variable myRectangle to some Ellipse1 or etc but its an ellipse and
Ellipse myellipse = new Ellipse();//name of variable doesnt matter(for some who think its a keyword or name to be written in the
myRectangle.Width = 100;//same fashion
myRectangle.Height = 100;
myRectangle.Stroke = new SolidColorBrush(Colors.Blue);
myRectangle.StrokeThickness = 5;
myRectangle.Fill = new SolidColorBrush(Colors.Red);
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.VerticalAlignment = VerticalAlignment.Top;
myRectangle.RenderTransform = rotatetransform;//Associate the rotatetransform to the UI element

myellipse.Width = 100;
myellipse.Height = 100;
myellipse.Stroke = new SolidColorBrush(Colors.Blue);
myellipse.StrokeThickness = 5;
myellipse.Fill = new SolidColorBrush(Colors.Red);
myellipse.Margin = new Thickness(1266, 0, 0, 0);//To push the UI element to right side of the screen(margin is declared based on

//screen size of 1366X768 pixels and will be different if your screen resolution is different

//to calculate the margin u can take (x=Width of your screen-100) as the width of UI element is 100
myellipse.RenderTransform = rotatetransform;//Associate the rotatetransform to the UI element

grid.RenderTransform = translatetransform;
// Add the rectangle to the tree.

LayoutRoot.Children.Add(grid);   //Grid is added in LayoutRoot that is Canvas which is declared in XAML
grid.Children.Add(myRectangle);  //Two ellipses are added into the declared grid so as to animate them in Y-axis
grid.Children.Add(myellipse);
// Create a duration of 10(userdefined can edit) seconds.
Duration duration = new Duration(TimeSpan.FromSeconds(10));  //Set the duration for which the animation should run

// Create three DoubleAnimations and set their properties.
DoubleAnimation myDoubleAnimation1 = new DoubleAnimation();
DoubleAnimation myDoubleAnimation2 = new DoubleAnimation();
DoubleAnimation gridanim = new DoubleAnimation();

myDoubleAnimation1.Duration = duration;
myDoubleAnimation2.Duration = duration;
gridanim.Duration = duration;

Storyboard sb = new Storyboard();
sb.RepeatBehavior = RepeatBehavior.Forever;//RepeatBehaviour declared in this line for the storyboard

sb.Children.Add(myDoubleAnimation1);//All the animations added to the storyboard
sb.Children.Add(myDoubleAnimation2);
sb.Children.Add(gridanim);

Storyboard.SetTarget(myDoubleAnimation1, myRectangle);
Storyboard.SetTarget(myDoubleAnimation2, myellipse);
Storyboard.SetTarget(gridanim, grid);

// Set the attached properties of Ellipse to RotateTransform to animate its Angle property
// to be the target properties of the two respective DoubleAnimations.

//To animate the Grid to TranslateTransfrom to animate its Y-axis position
Storyboard.SetTargetProperty(myDoubleAnimation1,”(Ellipse.RenderTransform).(RotateTransform.Angle)”);
Storyboard.SetTargetProperty(myDoubleAnimation2, “(Ellipse.RenderTransform).(RotateTransform.Angle)”);
Storyboard.SetTargetProperty(gridanim, “(Grid.RenderTransform).(TranslateTransform.Y)”);

gridanim.From = 0;    //Grid is animated to move from 0 to 768 pixels
gridanim.To = 768;
myDoubleAnimation1.From = 0;  //The two Ellipse are animated to rotate from 0 to 360 degrees
myDoubleAnimation1.To = 360;
myDoubleAnimation2.From = 0;
myDoubleAnimation2.To = 360;
// Make the Storyboard a resource because all storyboards are added as a resource to the Page(MainPage in this context)
LayoutRoot.Resources.Add(“unique_id”, sb);

// Begin the animation.
sb.Begin();
}

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name=”e”>Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
}
}

Try to paste the code and run it and also try to edit the things so you can understand the purpose of the line of code written.

[DataReadWrite]Reading and Writing data(text) in C#-XAML

Usings Req:
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Provider;
using System.Windows;
using System.Text;
using Windows.UI.Text;

Code(xaml.cs):
//Writing the text to a file

async private void save_Click(object sender, RoutedEventArgs e)
        {
            FileSavePicker savepicker = new FileSavePicker();
            savepicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;

            savepicker.FileTypeChoices.Add("Text", new List() { ".txt" });
            savepicker.FileTypeChoices.Add("Word 97-2003", new List() { ".doc" });

            savepicker.SuggestedFileName = "New Document";

            StorageFile file = await savepicker.PickSaveFileAsync();
            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);

                await FileIO.WriteTextAsync(file, main_text.Text);//main_text is the textbox name 

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status == FileUpdateStatus.Complete)
                {
                    output.Text = "File " + file.Name + " saved.";
                }
                else
                {
                    output.Text = "File " + file.Name + "couldn't be saved";
                }
            }
        }

//Reading the text from a file

async private void open_Click(object sender, RoutedEventArgs e)
        {
            Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Clear();

            FileOpenPicker openpicker = new FileOpenPicker();
            openpicker.FileTypeFilter.Add(".txt");
            openpicker.FileTypeFilter.Add(".doc");

            StorageFile file = await openpicker.PickSingleFileAsync();
            try 
            {
                if (file != null)
                {
                    string fileContent = await FileIO.ReadTextAsync(file);
                    main_text.Text = fileContent;
                    output.Text = "File " + file.Name + " opened.";//output is the textbox name
                }
            }
            catch
            {
                output.Text = "File couldn't be opened";
            }
        }

[ColorAnimation]Animating Background Color of an UI element

As most of us want to animate our apps to make it more attractive here is a sample for ColorAnimation property of the UI element.

ColorAnimation changes color of the UI element for a specific duration given in the storyboard.

The MainPage.xaml code:

<Page
x:Class=”App15.MainPage”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
xmlns:local=”using:App15″
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243;
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;
mc:Ignorable=”d”>
<Page.Resources>
<Storyboard x:Name=”sb”>
<ColorAnimation RepeatBehavior=”Forever” AutoReverse=”True”
From=”Green” To=”Violet”
Duration=”0:0:10″
Storyboard.TargetName=”root”
Storyboard.TargetProperty=”(Grid.Background).(SolidColorBrush.Color)”
EnableDependentAnimation=”True”
d:IsOptimized=”True”/>
</Storyboard>
</Page.Resources>
<Grid x:Name=”root” Background=”{StaticResource ApplicationPageBackgroundThemeBrush}”/>
</Page>

Mainpage.xaml.cs code:

using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace App15//(your project name or the name you gave to your project appears here)
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
sb.Begin();//To begin the animation Only paste this line after creating a blank project

}

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name=”e”>Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{

}
}
}

Copy and paste the above lines of code after creating a blank project.Follow the video for more!!!

[TUTORIAL]Adding Animations Dynamically(Programmatically) in C# XAML

This tutorial describes the procedure to add animation dynamically instead of xaml so that you can interact with the UI elements via Backend Code.

The MainPage.xaml code is here:

<Page
x:Class=”App12.MainPage”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
xmlns:local=”using:App12″
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243;
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;
mc:Ignorable=”d”>

<Canvas Name=”LayoutRoot” Background=”{StaticResource ApplicationPageBackgroundThemeBrush}”/>
</Page>

App12(bold letter) is my project name so the name of the project you gave will appear here.

The Backend Coding i.e MainPage.xaml.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Shapes;
using Windows.UI;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace App12
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();

Grid grid = new Grid();

RotateTransform rotatetransform = new RotateTransform();
rotatetransform.Angle = 0;
rotatetransform.CenterX = 50;
rotatetransform.CenterY = 50;

TranslateTransform translatetransform = new TranslateTransform();
translatetransform.X = 0;
translatetransform.Y = 0;

Ellipse myRectangle = new Ellipse(); //Sorry I didnt rename the variable myRectangle to some Ellipse1 or etc but its an ellipse and
Ellipse myellipse = new Ellipse();//name of variable doesnt matter(for some who think its a keyword or name to be written in the
myRectangle.Width = 100;//same fashion
myRectangle.Height = 100;
myRectangle.Stroke = new SolidColorBrush(Colors.Blue);
myRectangle.StrokeThickness = 5;
myRectangle.Fill = new SolidColorBrush(Colors.Red);
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.VerticalAlignment = VerticalAlignment.Top;
myRectangle.RenderTransform = rotatetransform;//Associate the rotatetransform to the UI element

myellipse.Width = 100;
myellipse.Height = 100;
myellipse.Stroke = new SolidColorBrush(Colors.Blue);
myellipse.StrokeThickness = 5;
myellipse.Fill = new SolidColorBrush(Colors.Red);
myellipse.Margin = new Thickness(1266, 0, 0, 0);//To push the UI element to right side of the screen(margin is declared based on

//screen size of 1366X768 pixels and will be different if your screen resolution is different

//to calculate the margin u can take (x=Width of your screen-100) as the width of UI element is 100
myellipse.RenderTransform = rotatetransform;//Associate the rotatetransform to the UI element

grid.RenderTransform = translatetransform;
// Add the rectangle to the tree.

LayoutRoot.Children.Add(grid);   //Grid is added in LayoutRoot that is Canvas which is declared in XAML
grid.Children.Add(myRectangle);  //Two ellipses are added into the declared grid so as to animate them in Y-axis
grid.Children.Add(myellipse);
// Create a duration of 10(userdefined can edit) seconds.
Duration duration = new Duration(TimeSpan.FromSeconds(10));  //Set the duration for which the animation should run

// Create three DoubleAnimations and set their properties.
DoubleAnimation myDoubleAnimation1 = new DoubleAnimation();
DoubleAnimation myDoubleAnimation2 = new DoubleAnimation();
DoubleAnimation gridanim = new DoubleAnimation();

myDoubleAnimation1.Duration = duration;
myDoubleAnimation2.Duration = duration;
gridanim.Duration = duration;

Storyboard sb = new Storyboard();
sb.RepeatBehavior = RepeatBehavior.Forever;//RepeatBehaviour declared in this line for the storyboard

sb.Children.Add(myDoubleAnimation1);//All the animations added to the storyboard
sb.Children.Add(myDoubleAnimation2);
sb.Children.Add(gridanim);

Storyboard.SetTarget(myDoubleAnimation1, myRectangle);
Storyboard.SetTarget(myDoubleAnimation2, myellipse);
Storyboard.SetTarget(gridanim, grid);

// Set the attached properties of Ellipse to RotateTransform to animate its Angle property
// to be the target properties of the two respective DoubleAnimations.

//To animate the Grid to TranslateTransfrom to animate its Y-axis position
Storyboard.SetTargetProperty(myDoubleAnimation1,”(Ellipse.RenderTransform).(RotateTransform.Angle)”);
Storyboard.SetTargetProperty(myDoubleAnimation2, “(Ellipse.RenderTransform).(RotateTransform.Angle)”);
Storyboard.SetTargetProperty(gridanim, “(Grid.RenderTransform).(TranslateTransform.Y)”);

gridanim.From = 0;    //Grid is animated to move from 0 to 768 pixels
gridanim.To = 768;
myDoubleAnimation1.From = 0;  //The two Ellipse are animated to rotate from 0 to 360 degrees
myDoubleAnimation1.To = 360;
myDoubleAnimation2.From = 0;
myDoubleAnimation2.To = 360;
// Make the Storyboard a resource because all storyboards are added as a resource to the Page(MainPage in this context)
LayoutRoot.Resources.Add(“unique_id”, sb);

// Begin the animation.
sb.Begin();
}

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name=”e”>Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
}
}

Try to paste the code and run it and also try to edit the things so you can understand the purpose of the line of code written.


Leave a comment